Question

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"); 
}
}); 
Was it helpful?

Solution

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);

}

}

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