Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have program wait for a button press in Java

Tags:

java

swing

Now, I'm not sure if this is possible or even the best way to accomplish what I'm trying to do, but basically I'm creating a very simple simulation program with a very simple Swing GUI.

After each round of the simulation, some buttons on the interface are enabled for the user to make changes and then the user can press the "continue" button to start the simulation again. The simulation itself is basically a while loop that needs to wait for the user action before continuing. My question is how can I have the program stop and wait until the user presses the "continue" button? Please let me know if there are any more details I can provide if this is unclear!

Edit:

I'm going to add some simplified code here so maybe this will make more sense. The program is in two parts, the simulation class and the view. So the button to be pressed is in the view class while the simulation is happening in its class.

Simulation class:

SimulationView view = new SimulationView(); // extends JFrame

while (!some_condition) {
    // code
    // need user action via button press here before continuing!
}
like image 288
seth Avatar asked Jan 30 '26 03:01

seth


1 Answers

Most likely the best way to go is enclose one round of the simulation in a method, that would then be executed from the action listener attached to the button you want.

After edit: Somebody needs to control the simulation in the first place, so you could do the following:

SimluationClass
{
    public int startSim()
    {
      ...
    }
}

class SimulationView
{

    SimulationClass sim = new SimulationClass();      

    private void init()
    {

      JButton button = new JButton("Start");
      button.addActionListener(new ActionListener() {
          void actionPerformed(...) 
          {
               sim.startSim()
          }
          });
    }
}

Keep in mind though that this will freeze your gui as the sim method will be executed from the event thread.

like image 163
Greg Adamski Avatar answered Jan 31 '26 15:01

Greg Adamski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!