JDialog 取消按钮
如何在 Swing JDialog 中设置取消按钮,即当用户按下键盘上的“取消”键时自动执行操作的按钮?
通过对话框根窗格的 setDefaultButton
方法提供对应的默认操作。
如果这有帮助,我正在寻找 WinForms Form.CancelButton 属性的类似物。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我能看到的最好方法是将
Action
添加到根窗格的操作映射,并使用根窗格的输入映射将该操作链接到转义键。为此,您需要一个
Action
。 如果取消按钮的行为是作为操作实现的(即cancelButton.getAction() != null
),那么这将起作用:否则,如果取消按钮的逻辑是通过 ActionListener 实现的,您可以让
ActionListener
的actionPerformed()
方法调用实现逻辑的private void onCancel()
方法,并注册一个调用相同方法的“取消”操作。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:Otherwise, if the cancel button's logic is implemented via an
ActionListener
, you could have theactionPerformed()
method of theActionListener
call aprivate void onCancel()
method that implements the logic, and register a "cancel" action that calls the same method.单行解决方案
,其中 t 是对话框中的任何组件(JButton 除外),例如 JTextField。
Single line solution
where t is any component(except JButton) like JTextField in the dialog.
我认为如果不扩展 JDialog,这是不可能的。
您可以使用 JOptionPane.showOptionDialog() (或者可能是其他显示方法之一),传递您想要使用的 JButton。
如果传递的选项是组件,它们将正常渲染,因此您可以执行以下操作:
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:
您所要做的就是将操作侦听器附加到按钮并在其中调用
dialog.setVisible(false)
。All you have to do is attach the action listener to the button and call
dialog.setVisible(false)
inside of it.