JDialog cancel button

六眼飞鱼酱① 提交于 2019-12-08 17:42:00

问题


How can I set a cancel button in a Swing JDialog, i.e. a button whose action is performed automatically if the user presses the “Cancel” key on the keyboard?

The counterpart is offered for a default action via the setDefaultButton method of the dialog's root pane.

If that's helping, I'm searching for an analogue to the WinForms Form.CancelButton property.


回答1:


I don't think this is possible with JDialog without extending it.

You could use JOptionPane.showOptionDialog() (or possibly one of the other show methods), passing the JButtons you want to be used.

If the options passed are components, they'll be rendered as normal, so you can do something like this:

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:


The best way I can see is to add an Action to the action map of the root pane, and link that action to the escape key using the root pane's input map.

For this, you need an Action. If your cancel button's behaviour is implemented as an action (ie. cancelButton.getAction() != null), then this will work:

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

Otherwise, if the cancel button's logic is implemented via an ActionListener, you could have the actionPerformed() method of the ActionListener call a private void onCancel() method that implements the logic, and register a "cancel" action that calls the same method.

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:


Single line solution

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

where t is any component(except JButton) like JTextField in the dialog.




回答4:


All you have to do is attach the action listener to the button and call dialog.setVisible(false) inside of it.



来源:https://stackoverflow.com/questions/1284328/jdialog-cancel-button

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!