0

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?

Alex Jj
  • 1,343
  • 10
  • 19
  • 30

5 Answers5

2

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.

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
  • Thank you for your answer but did not work: it give an error for myInput.getText(). here is the error: Cannot refer to a non-final variable myInput inside an inner class defined in a different method – Alex Jj Mar 28 '13 at 13:20
  • So you need to declare the textfield as a instance variable. That way you will have proper access to it from within the inner class. – Vincent Ramdhanie Mar 28 '13 at 13:24
1

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.

tckmn
  • 57,719
  • 27
  • 114
  • 156
  • Thank you for your answer but did not work: it give an error for myInput.getText(). here is the error: Cannot refer to a non-final variable myInput inside an inner class defined in a different method – Alex Jj Mar 28 '13 at 13:19
1
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.

tmwanik
  • 1,643
  • 14
  • 20
  • Thanks for reply. When I move the second line inside the action listener it gives the same error as system.out.print(myInput.getText); does which the error is: Cannot refer to a non-final variable myInput inside an inner class defined in a different method – Alex Jj Mar 28 '13 at 13:22
1

take the 2nd line inside the action performed method

  • I don't see why you want to set it as Final, I think it may cause trouble if u wanna change the value of it after you set it for the 1st time – Moayad Al-sowayegh Mar 28 '13 at 14:36
0

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.

Alex Jj
  • 1,343
  • 10
  • 19
  • 30