【发布时间】:2016-01-14 04:59:03
【问题描述】:
所以我知道在这个网站上和一般的互联网上都有很多类似的问题,但我一直无法找到确切的答案或满足我想要完成的目标的答案。
我的程序中有多个JOptionPanes。所有这些JOptionsPanes 在顶角都有一个“X”。目前,它们的功能与任何其他 JOptionPane 的默认按钮相同。
如果用户单击“X”,我希望程序退出。使用任何其他按钮,屏幕将关闭,但使用“X”我想引发System.exit(0) 类型的事件。
我尝试使用if 语句来实现这一点,例如:
int result = JOptionPane.showOptionDialog(null, getPanel(),"Return Builder", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, "default");
if(result==JOptionPane.CLOSED_OPTION){
System.exit(0);
}
但我发现无论用户点击哪个按钮,整个程序都会退出。即使他们单击了我的其他具有动作侦听器的JButtons 之一,程序仍然会退出。我将发布这个特定 GUI 的更完整图片:
public static void displayGUI(){//Method to display the GUI.
final JButton buttonCreate = new JButton("Create Return");
final JButton buttonConfirm = new JButton("Confirm");
buttonConfirm.addActionListener(new ActionListener(){
public void actionPerformed(final ActionEvent ae){
if(output.getSize()>0){
JOptionPane.getRootFrame().dispose();
}else if(verifyBatch==true){
JOptionPane.getRootFrame().dispose();
}else if(verifyBatch==false && output.getSize()==0){
JOptionPane.showMessageDialog(null, "You haven't added any transactions to confirm" +
" and you have no previously completed batches!");
}
}
});
buttonCreate.addActionListener(new ActionListener(){
public void actionPerformed(final ActionEvent ae){
if(verifyBatch==true){
initialScreenDecisions="NONE";//The user did not choose to add any entry details to the output list.
MainWriter.finishedCounter=true;//The boolean counter to trigger that the return is finished goes to true.
while(MainWriter.entryDetails.size()>0){//Removes all entry details from the input list.
MainWriter.entryDetails.remove(0);
}
while(output.size()>0){//Removes all entry details from the output list..
output.remove(0);
}
JOptionPane.getRootFrame().dispose();
}else{
JOptionPane.showMessageDialog(null, "There are no completed batches!");
}
}
});
//Creates a JOptionPane for the first GUI featuring 7 buttons and 2 lists..
final Object[] options = new Object[] {buttonConfirm,buttonCreate};
int result = JOptionPane.showOptionDialog(null, getPanel(),"Return Builder", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, "default");
if(result==JOptionPane.CLOSED_OPTION){
System.exit(0);
}
}
那么从这个例子中,我怎样才能让“X”和只有“X”退出整个程序?我还有许多其他JOptionsPanes 我需要实施类似的措施。
【问题讨论】:
-
Afaik 按 [x] 关闭窗口与按取消按钮相同。您必须生成自己的 JDialog 才能确定用户用来关闭窗口的实际机制
-
所以如果不使用 JOptionsPane 以外的东西,就没有办法从逻辑上说“如果用户单击“X”关闭程序”?
-
我没有仔细研究过 JavaDocs,但我似乎记得从
JOptionPaneAPI 的角度来看 [Cancel] 和 [x] 是一回事,您需要创建自己的JDialog并添加JOptionPane如果您想了解更多信息 -
感谢您的评论。我会将其标记为完成,但您没有将其设置为答案。
-
@MadProgrammer 它们是不同的返回值:
YES_OPTION、NO_OPTION、CANCEL_OPTION、OK_OPTION和CLOSED_OPTION。
标签: java swing joptionpane