因此,我尝试运行代码,打开GUI窗口,在两个按钮之间进行选择,这两个按钮设置了一个值,然后使用此值继续其余的代码。
我见过类似的问题或教程,但是找不到适合我问题的解决方案。
正如我已经看到的,必须使用JFrame,ActionListener和ActionEvent才能创建带有按钮的GUI。
在main方法中编写了一个扩展JFrame并实现ActionListener的对象。
问题是,在main方法中编写的代码会打开GUI窗口并继续运行。我只希望代码一直等到用户单击按钮然后继续。
一个子解决方案是,在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);
}
}
在程序开始时,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!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句