我的程序包含两个类,一个代表主程序,另一个是使用swing实现的gui,
我正在尝试创建一个“事件类型”,这意味着我希望我的主程序等待,直到用户界面(GUI)指示某些事件,例如按下按钮,并且我想在按钮时发送一些信息被按下。
主程序的通用代码(这是相关部分)
// Open window GUI with the requested BID and wait for confirmation or denial
HumanIFWindow nextWindowGUI = new HumanIFWindow();
nextWindowGUI.setVisible(true);
// ----------------- //
// - Wait on event - //
// ----------------- //
// Here is where I want to wait for the gui Indication
return returnedBid;
GUI 代码(同样仅相关部分)
JButton btnAprove = new JButton("Aprove");
btnAprove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ----------------- //
// - Trigger event - //
// ----------------- //
// Here is where I want to trigger the event
}});
我最好想使用一些库,有一个符合我的需求吗? (也许是巴士 Activity ?)
编辑以指定问题(感谢 Kishan Sarsecha Gajjar)
我希望第一个类(一般类)输入等待语句,我知道如何等待使用:
while( someBoolean...)
Thread.sleep(...)
我可以用 GUI 类中的句柄更改 someBoolean,例如:
FisrtClass.someBoolean == False
但我想要一些更好、更简洁的东西,比如一个实现 sleep 语句的库。并且不需要额外的代码。有这样的事吗? 我查看了 Google-BusEvent 库,但不确定它是否兼容
编辑,添加 JDialog
更新的代码:主程序:
Bid returnedBid = requestBid;
// Open window GUI with the requested BID and wait for confirmation
DialogHumanConfirmManual nextWindowGUI = new DialogHumanConfirmManual(requestBid);
// Wait on event
if ( (returnedBid = nextWindowGUI.getAnswer()) != null ){
System.out.println("Got Bid " + returnedBid.print());
}
GUI - 对话框:
public DialogHumanConfirmManual(Bid requestedBid){
currentBid = requestedBid;
currentBid.approvedHuman = false;
Dialog mainFrame = new Dialog(new Frame());
myPanel = new JPanel();
getContentPane().add(myPanel);
myPanel.add(new JLabel("Confirmation Dialog"));
yesButton = new JButton("Confirm");
yesButton.addActionListener(this);
myPanel.add(yesButton);
noButton = new JButton("No");
noButton.addActionListener(this);
myPanel.add(noButton);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (yesButton == e.getSource()) {
currentBid.approvedHuman = true;
answeredBid = currentBid;
}
}
打开对话框后,调用 if ( returnBid ),这会导致代码中出现空指针异常,那么我如何延迟主程序直到用户可以确认请求?
最佳答案
the other one is a gui implemented using swing,
使用模态 JDialog
而不是 JFrame。
一旦对话框可见,setVisible(true) 语句之后的代码将不会执行,直到对话框关闭。
阅读 Swing 教程中关于 How to Make Dialogs 的部分了解更多信息。本教程涵盖了 JOptionPane 类,但您可以只使用 JDialog,它的创建方式与 JFrame 完全相同。您可以根据您的具体要求选择使用 JOptionPane 还是 JDialog。
关于swing - java中的"Events type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23297975/