【问题标题】:Creating Dialog from JOptionPane and working on OK_CANCEL_OPTION [duplicate]从 JOptionPane 创建对话框并处理 OK_CANCEL_OPTION [重复]
【发布时间】:2013-02-05 07:34:40
【问题描述】:

我有一个从用户那里收集两个字符串的自定义对话框。创建对话框时,我使用 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);

// 按下 OK 时在此处执行操作,按下取消时仅处理。

/注意:请不要向我推荐 JOptionPane.ShowOptionDialog(*****);** 的方式这个问题是因为我知道这种方式,但我需要上面提到的为“确定”和“取消”按钮设置操作的方式。*/

【问题讨论】:

  • 请这个问题是关于的,阅读Oracle教程,在这个论坛上搜索

标签: java swing joptionpane


【解决方案1】:

这对我有用:

...
JOptionPane pane = new JOptionPane(message,  JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog getTopicDialog =  pane.createDialog(null, "New Topic");
getTopicDialog.setVisible(true);
if(null == pane.getValue()) {
    System.out.println("User closed dialog");
}
else {
    switch(((Integer)pane.getValue()).intValue()) {
    case JOptionPane.OK_OPTION:
        System.out.println("User selected OK");
        break;
    case JOptionPane.CANCEL_OPTION:
        System.out.println("User selected Cancel");
        break;
    default:
        System.out.println("User selected " + pane.getValue());
    }
}

【讨论】:

    【解决方案2】:

    根据documentation,您可以使用 pane.getValue() 来了解单击了哪个按钮。 来自文档:

    直接使用:直接创建和使用JOptionPane,标准模式大致如下:

         JOptionPane pane = new JOptionPane(arguments);
         pane.set.Xxxx(...); // Configure
         JDialog dialog = pane.createDialog(parentComponent, title);
         dialog.show();
         Object selectedValue = pane.getValue();
         if(selectedValue == null)
           return CLOSED_OPTION;
         //If there is not an array of option buttons:
         if(options == null) {
           if(selectedValue instanceof Integer)
              return ((Integer)selectedValue).intValue();
           return CLOSED_OPTION;
         }
         //If there is an array of option buttons:
         for(int counter = 0, maxCounter = options.length;
            counter < maxCounter; counter++) {
            if(options[counter].equals(selectedValue))
            return counter;
         }
         return CLOSED_OPTION;
    

    希望对你有帮助,

    【讨论】:

      猜你喜欢
      • 2015-03-08
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      相关资源
      最近更新 更多