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 */
  }
});
Description
上記のサンプルでは、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()); }
 
- デフォルトの
- 右上: WindowListener- JOptionPane#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()); }
 
- 左下: HierarchyListener- textFieldに- 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()); }
 
- 右下: AncestorListener- textFieldに- addAncestorListenerを追加し- ancestorAddedが呼ばれたときに- textField.requestFocusInWindow();を実行
- Swing - Input focus