phi*_*b28 6 java swing jdialog joptionpane
我有一个自定义对话框,从用户收集两个字符串.我在创建对话框时使用OK_CANCEL_OPTION作为选项类型.Evertyhings有效,除非用户单击取消或关闭对话框时单击确定按钮具有相同的效果.
我该如何处理取消和关闭事件?
继承我正在谈论的代码:
JTextField topicTitle = new JTextField();
JTextField topicDesc = new JTextField();
Object[] message = {"Title: ", topicTitle, "Description: ", topicDesc};
JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog getTopicDialog = pane.createDialog(null, "New Topic");
getTopicDialog.setVisible(true);
// Do something here when OK is pressed but just dispose when cancel is pressed.
Run Code Online (Sandbox Code Playgroud)
我认为对您来说更好的选择是使用以下代码
JTextField topicTitle = new JTextField();
JTextField topicDesc = new JTextField();
Object[] message = {"Title: ", topicTitle, "Description: ", topicDesc};
Object[] options = { "Yes", "No" };
int n = JOptionPane.showOptionDialog(new JFrame(),
message, "",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
options, options[1]);
if(n == JOptionPane.OK_OPTION){ // Afirmative
//....
}
if(n == JOptionPane.NO_OPTION){ // negative
//....
}
if(n == JOptionPane.CLOSED_OPTION){ // closed the dialog
//....
}
Run Code Online (Sandbox Code Playgroud)
通过使用 showOptionDialog 方法,您将根据用户的行为获得结果,因此除了解释该结果外,您无需执行任何其他操作