JDialog取消按钮

问题描述:

如何在 Swing JDialog 中设置取消按钮,即如果用户按下键盘上的取消"键,其动作将自动执行的按钮?

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?

通过对话框根窗格的 setDefaultButton 方法为默认操作提供对应项.

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

如果这有帮助,我正在寻找类似于 WinForms Form.CancelButton 属性的内容.

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

如果不扩展 JDialog,我认为这是不可能的.

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

您可以使用 JOptionPane.showOptionDialog()(或可能是其他显示方法之一),传递您想要使用的 JButton.

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]);