JOptionPaneのデフォルトフォーカス
Total: 11175, Today: 1, Yesterday: 2
Posted by aterai at
Last-modified:
Summary
JOptionPaneにデフォルトでフォーカスをもつコンポーネントを追加します。
Screenshot

Advertisement
Source Code Examples
textField4.addAncestorListener(new AncestorListener() {
@Override public void ancestorAdded(AncestorEvent e) {
e.getComponent().requestFocusInWindow();
}
@Override public void ancestorMoved(AncestorEvent e) {
/* not needed */
}
@Override public void ancestorRemoved(AncestorEvent e) {
/* not needed */
}
});
View in GitHub: Java, KotlinDescription
上記のサンプルでは、JOptionPane.showConfirmDialogで表示するJTextFieldにデフォルトのフォーカスがあたるように設定しています。
- 左上:
Default- デフォルトの
ConfirmDialogの場合、初期フォーカスは入力欄ではなくOKボタンにあるint result = JOptionPane.showConfirmDialog( frame, textField, "Input Text", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { textArea.setText(textField.getText()); }
- デフォルトの
- 右上:
WindowListenerJOptionPane#createDialog(...)でJDialogを取得しWindowListener#windowOpenedでtextField.requestFocusInWindow();を実行- Windowを開いたときのフォーカスを指定など
JOptionPane pane = new JOptionPane( textField, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, null, null); JDialog dialog = pane.createDialog(frame, "Input Text"); dialog.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { textField.requestFocusInWindow(); } }); dialog.setVisible(true); Object selectedValue = pane.getValue(); int result = JOptionPane.CLOSED_OPTION; if (selectedValue != null && selectedValue instanceof Integer) { result = ((Integer) selectedValue).intValue(); } if (result == JOptionPane.OK_OPTION) { textArea.setText(textField.getText()); }
- 左下:
HierarchyListenertextFieldにHierarchyListenerを追加しhierarchyChangedが呼ばれたときにtextField.requestFocusInWindow();を実行textField3.addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && textField3.isShowing()) { EventQueue.invokeLater(new Runnable() { @Override public void run() { textField3.requestFocusInWindow(); } }); } } }); int result = JOptionPane.showConfirmDialog( frame, textField3, "Input Text", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { textArea.setText(textField3.getText()); }
- 右下:
AncestorListenertextFieldにaddAncestorListenerを追加しancestorAddedが呼ばれたときにtextField.requestFocusInWindow();を実行- Swing - Input focus