0

How can I change the Value of a JTextfield inside an ActionLIstener?

cmdAnzeigen.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e)
{
/* Cannot refer to a non-final variable TextOutput inside an 
     inner class defined in a different method*/
    TextOutput.setText("Hello"); 
}
}); 
Vinay Veluri
  • 6,671
  • 5
  • 32
  • 56
  • 1
    Well, make the variable final, as the error message suggests. Also, variables should start with a lowercase letter in Java. And pasting the error message in google would lead you to dozens of explanations. – JB Nizet Mar 25 '14 at 07:30
  • And follow Java naming convention. variables should begin with lower case letters using camel casing. – Paul Samsotha Mar 25 '14 at 07:33

1 Answers1

0

Here,You can write another method and put your TextField value change code in this method. like,

public class Demo {
static JTextField txtName;
static JButton jbSubmit;
public Demo()
{
    txtName = new JTextField(10);
    jbSubmit = new JButton("Submit");
    jbSubmit.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            change("XYZ");
            }
    });

}
public static void change(String name)
{
    txtName.setText(name);
}

public static void main(String[] args) {
    Demo d = new Demo();

    JFrame jf=new JFrame();
    jf.add(txtName);
    jf.add(jbSubmit);
    jf.setLayout(new FlowLayout());
    jf.setVisible(true);
    jf.setSize(500,200);

}

}

chintan
  • 471
  • 3
  • 16