How to make a program wait for a button to be pressed in Java

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 am creating a very simple simulation program with a very simple Swing GUI.

After each round of modeling, some buttons on the interface allow the user to make changes, and then the user can click 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 stop the program and wait for the user to click the continue button? Please let me know if there are any details that I can provide if this is unclear!

Edit:

I'm going to add some simplified code, so maybe this will make more sense. The program consists of two parts: a modeling class and a presentation. Thus, the button to be pressed is in the view class while the simulation is in its class.

Simulation Class:

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

while (!some_condition) {
    // code
    // need user action via button press here before continuing!
}
+3
source share
1 answer

Most likely, the best way is to enclose one round of modeling in a method, which will then be executed from an action listener attached to the desired button.

After editing: Someone should control the simulation first, so you can 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 that this will freeze your gui, as the sim method will be executed from the event stream.

+5
source

Source: https://habr.com/ru/post/1724441/


All Articles