Domanda

I have a JTextField in my program which I hooked up a Keyboard Listener to through the use of an anonymous inner class. the listener clears the text box and saves the word currently on it.

I want to be able to use that word I got out of it in other parts of the code but I know all variables used in inner classes have to be tagged final.. so how do I do this?

here's my simplified code to give you guys an idea - I want to be able to use userWord

    typingArea.addKeyListener(new KeyAdapter() {
        public void keyPressed (KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) { // enter key is pressed
                userWord = typingArea.getText().toLowerCase();
                typingArea.setText("");

            }
        }
    });

EDIT: Just had the idea of maybe passing it as a constructor variable to another object I can create which would then be able to extract and save that string.. would this work? Sorry for the pointless question if I literally thought of a solution a second after asking, haha.

È stato utile?

Soluzione

  1. Use an ActionListener instead of a KeyListener and KeyEvent.VK_ENTER - lots of reasons why, but basically, this is what an ActionListener was designed to do.
  2. Use a class field instead of a local variable...

More like...

public class MyForm extends JPanel {

    private JTextField typingArea;
    private String userWord; 

    public MyForm() {

        typingArea = new JTextField();
        typingArea.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                userWord = typingArea.getText().toLowerCase();
                typingArea.setText("");
            }
        });
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top