Skip to content
Advertisement

Update class variables on button click

If i click my “Run” button on my GUI after changing the value of a textfield, the variable won’t update.

I have the button in one class:

            public void actionPerformed(ActionEvent e) {
                
                RunSimulation r = new RunSimulation();
                System.out.println(Data.campusSize);
                System.out.println("Button clicked!");
            }
        });

and in another class, i have all my Data collected:

public class Data { 
static int campusSize = Integer.valueOf(View.campusSizeTextField.getText()); 
}

in the RunSimulation class, the class variables in Data are accessed. If I print out Data.campusSize, it will always give the same value, even if I change it in the textField.

Advertisement

Answer

The problem with your current code is that your campusSize variable isn’t updated each time you change the value in the UI. The only time the getter for that UI component is called, is when you initialize your int.

A simple way to change your code:

public void actionPerformed(ActionEvent e) {                
  RunSimulation r = new RunSimulation();
  System.out.println(Data.getCampusSize());
  System.out.println("Button clicked!");
}

Notice that now, I call a method, not an already instantiated variable.

public class Data { 
  public static int getCampusSize() {
    return Integer.valueOf(View.campusSizeTextField.getText());
  } 
}

This way, you’ll get the updated value of your textField each time you call that method, since you call the getter again.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement