Search code examples
javaswingvariablesjtextfield

Get the value from a JTextField & re-write it into an existing variable


Get the value from a JTextField & re-write it into an existing variable.

example:

public class variables{

     String var = "hi";

  public static void main(String[]args){

  //do sth    

  }

}

then interface reads the value from the main class & change the value from a JTextField

private void changeVariableActionPerformed(java.awt.event.ActionEvent evt) {                                               


  variables.var = txtField.getText();

  //then into textfield we write bye  & variables.var takes the value of bye

  //variables.var = "bye"

}  

I want to change the Value of var with the action perform


Solution

  • Add ActionLister to the JTextField and each time you change the value assign it to you variable.

    you could do something like this:

    txtField.addActionListener(new ActionListener() {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            variables.var = txtField.getText();
    
         }
     });