想要暂停代码直到用户使用按钮

Want to halt code until user uses a button

所以我正在尝试 运行 一个代码,打开一个 GUI window,在两个按钮之间进行选择,这两个按钮设置一个值,然后使用该值继续其余的代码。

我看过类似的问题或教程,但没有找到适合我的问题的解决方案。

正如我已经看到的,必须使用JFrameActionListenerActionEvent为了制作带有按钮的 GUI。

在main方法中写了一个扩展JFrame并实现ActionListener的对象。

问题是,main 方法 中编写的代码会打开 GUI window 并继续 运行。我只希望代码等到用户单击按钮然后继续。

一个子解决方案是,在 actionPerformed 方法中编写我想要的代码但是:

或者编写一个 while 循环,直到单击一个按钮。必须存在一个更明智的解决方案,我不知道或者我不明白它应该如何工作。

这是部分代码。

@Override
     public void actionPerformed(ActionEvent e) {
        if(e.getSource() == testStringA) {
            setVariableTo = "testString_a";
            try {
                runMethodWithNewVariable(setVariableTo);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            System.exit(0);
        } else {
            setVariableTo = "project";
            try {
                runMethodWithNewVariable(setVariableTo);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            System.exit(0);
        }
     }

您基本上有两个线程 运行 - 主线程和 GUI 线程。您没有显式创建 GUI 线程,但它就在那里。

您可以使用多种技术来同步这两个线程。最基本的是旧的 synchronizedwaitnotify。也可以使用 Semaphore 的东西。在主线程中,您将创建 GUI 并等待直到满足条件。在 GUI 线程(即 actionPerformed)中,您会通知。

为什么不使用带有两个按钮的 JOptionPane (showOptionDialog) 而不是 JFrame,"string A" 和 "project" 而不是 "Yes" 和 "No",例如?

JOptionPanes 像 "show Option Dialog" 本质上是阻塞的。如果你把一个放在你的 main() 方法中,执行将 "wait" 让用户在对话框中 select 一些东西,并且对话框将 return 指示什么是 select在 main() 继续执行之前编辑。

在您的程序开始时,向用户显示模态 JDialog!您可以使用 JOptionPane.show() 方法执行此操作,如下所示:

String[] buttonTexts = {"first","second"}; //create the button texts here

//display a modal dialog with your buttons (stops program until user selects a button)
int userDecision =  JOptionPane.showOptionDialog(null,"title","Select a button!",JOptionPane.DEFAULT_OPTION,JOptionPane.PLAIN_MESSAGE,null,buttonTexts,buttonTexts[0]);

//check what button the user selected: stored in the userDecision
// if its the first (left to right) its 0, if its the second then the value is 1 and so on

if(userDecision == 0){
  //first button was clicked, do something
} else if(userDecision == 1) {
  //second button was clicked, do something
} else {
 //user canceled the dialog
}

//display your main JFrame now, according to user input!