如何让程序等待 Java 中的按钮按下 [英] How to have program wait for a button press in Java

查看:23
本文介绍了如何让程序等待 Java 中的按钮按下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我不确定这是否可能,甚至不确定是否是完成我想要做的事情的最佳方式,但基本上我正在创建一个非常简单的模拟程序,其中包含一个非常简单的 Swing GUI.

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.

每轮模拟结束后,界面上的一些按钮会被启用以供用户进行更改,然后用户可以按继续"按钮再次开始模拟.模拟本身基本上是一个while循环,需要等待用户操作才能继续.我的问题是如何让程序停止并等到用户按下继续"按钮?如果不清楚,请告诉我是否有更多细节我可以提供!

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!

我将在这里添加一些简化的代码,这样也许会更有意义.程序分为模拟类和视图两部分.所以要按下的按钮在视图类中,而模拟在其类中发生.

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.

模拟类:

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

while (!some_condition) {
    // code
    // need user action via button press here before continuing!
}

推荐答案

很可能最好的方法是将一轮模拟包含在一个方法中,然后从附加到您想要的按钮的动作侦听器中执行该方法.

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

请记住,这会冻结您的 gui,因为 sim 方法将从事件线程中执行.

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

这篇关于如何让程序等待 Java 中的按钮按下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆