代码之家  ›  专栏  ›  技术社区  ›  Konrad Rudolph

J对话框取消按钮

  •  7
  • Konrad Rudolph  · 技术社区  · 15 年前

    我怎么能在秋千中设置取消按钮呢 JDialog ,即当用户按下键盘上的__cancel_键时自动执行操作的按钮?

    对应方通过 setDefaultButton 对话框根窗格的方法。

    如果这有帮助的话,我正在寻找类似于WinForms的东西 Form.CancelButton 财产。

    4 回复  |  直到 12 年前
        1
  •  1
  •   Rich Seller    15 年前

    我认为如果JDialog不扩展它是不可能的。

    您可以使用joptionpane.showOptionDialog()(或者可能是其他show方法之一),传递您想要使用的jButton。

    如果传递的选项是组件,则它们将呈现为普通的,因此可以执行以下操作:

    int optionType = JOptionPane.DEFAULT_OPTION;
    int messageType = JOptionPane.PLAIN_MESSAGE; // no standard icon
    
    JButton ok = new JButton("ok");
    JButton cancel = new JButton("cancel");
    //add any handlers to the buttons
    ...
    //construct options
    Object[] selValues = { ok, cancel };
    
    //show dialog as normal, selected index will be returned.
    int res = JOptionPane.showOptionDialog(null, "message",
            "title", optionType, messageType, null, selValues,
            selValues[0]);
    
        2
  •  4
  •   Jon Bright    12 年前

    我能看到的最好方法是添加 Action 到根窗格的操作映射,并使用根窗格的输入映射将该操作链接到转义键。

    为此,您需要 行动 . 如果取消按钮的行为被实现为一个动作(即 cancelButton.getAction() != null ,这样就可以:

    getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "CANCEL");
    getRootPane().getActionMap().put("CANCEL", cancelButton.getAction());
    

    否则,如果取消按钮的逻辑是通过 ActionListener ,你可以有 actionPerformed() 方法 监听器 打电话给 private void onCancel() 方法,该方法实现逻辑,并注册调用同一方法的“取消”操作。

    getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "CANCEL");
    getRootPane().getActionMap().put("CANCEL", new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e)
        {
            onCancel();
        }
    });
    
        3
  •  2
  •   Prabu    15 年前

    单线解决方案

    t.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
       .put(KeyStroke.getKeyStroke("ESCAPE"), btnCancel.getAction());
    

    其中t是对话框中jtextfield等任何组件(jbutton除外)。

        4
  •  1
  •   Eugene Ryzhikov    15 年前

    你所要做的就是把动作监听器连接到按钮上,然后调用 dialog.setVisible(false) 里面。