Question

As a part of my program, I just want to print out what the user enters in the jTextField

here is what I do, but does not work at all.

JTextField myInput = new JTextField();
String word = myInput.getText();

myInput.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) 
{
System.out.print(word);
}

});

Any idea?

Was it helpful?

Solution

In the actionlistener you need to retrieve the value from the textfield.

 System.out.print(myInput.getText());

At the moment, you are getting a empty value because at the point where you call getText() there is nothing in the textfield because the user did not have time to type something.

OTHER TIPS

You aren't updating the text (word) in actionPerformed, so it's staying the same. Try:

myInput.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) 
{
System.out.print(myInput.getText());
}

Therefore, you don't even need to declare word at all.

take the 2nd line inside the action performed method

final JTextField myInput = new JTextField();

myInput.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        System.out.print(myInput.getText());
    }
});

Calling myInput.getText() outside the actionListener will assign empty string to word.

Thank you everyone for your answers. In fact you are all right and I just need to delcare the variable as final. I still do not know why I should add that but it's working now. I hope that 'final' doesn't make make any problem later.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top