如何在Swing JDialog
中设置取消按钮,即如果用户按下键盘上的“取消”键,其动作会自动执行的按钮?
通过对话框根窗格的setDefaultButton
方法提供对应的默认操作。
如果这有帮助,我正在寻找WinForms Form.CancelButton
属性的类似物。
答案 0 :(得分:4)
我能看到的最好方法是在根窗格的操作映射中添加Action
,并使用根窗格的输入映射将该操作链接到转义键。
为此,您需要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()
方法的ActionListener
方法可以调用实现逻辑的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(); } });
答案 1 :(得分:2)
单线解决方案
t.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke("ESCAPE"), btnCancel.getAction());
其中t是对话框中的任何组件(JButton除外),如JTextField。
答案 2 :(得分:1)
我认为如果没有扩展它,可以使用JDialog。
您可以使用JOptionPane.showOptionDialog()(或者可能是其他show方法之一),传递您想要使用的JButtons。
如果传递的选项是组件,它们将正常呈现,因此您可以执行以下操作:
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]);
答案 3 :(得分:1)
您所要做的就是将动作侦听器附加到按钮并在其中调用dialog.setVisible(false)
。