Swing にキャンセル ボタンJDialog、つまり、ユーザーがキーボードの「キャンセル」キーを押した場合にアクションが自動的に実行されるボタンを設定するにはどうすればよいですか?
setDefaultButton対応するものは、ダイアログのルート ペインのメソッドを介してデフォルト アクションに提供されます。
Form.CancelButtonそれが助けになる場合は、WinFormsプロパティの類似物を探しています。
私が見ることができる最善の方法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()ActionListenerprivate void onCancel()
getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "CANCEL");
getRootPane().getActionMap().put("CANCEL", new AbstractAction(){
@オーバーライド
public void actionPerformed(ActionEvent e)
{
onCancel();
}
});
単線ソリューション
t.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke("ESCAPE"), btnCancel.getAction());
t は、ダイアログ内の JTextField などの任意のコンポーネント (JButton を除く) です。
アクション リスナーをボタンにアタッチし、そのdialog.setVisible(false)中で呼び出すだけです。
JDialog を拡張しない限り、これは不可能だと思います。
JOptionPane.showOptionDialog() (または他の表示メソッドのいずれか) を使用して、使用する 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]);