• title: JOptionPaneのデフォルトフォーカス tags: [JOptionPane, Focus, JComponent, WindowListener, HierarchyListener, AncestorListener] author: aterai pubdate: 2009-11-23T19:41:03+09:00 description: JOptionPaneにデフォルトでフォーカスをもつコンポーネントを追加します。

概要

JOptionPaneにデフォルトでフォーカスをもつコンポーネントを追加します。

サンプルコード

textField4.addAncestorListener(new AncestorListener() {
  @Override public void ancestorAdded(AncestorEvent e) {
    e.getComponent().requestFocusInWindow();
  }
  @Override public void ancestorMoved(AncestorEvent e) {}
  @Override public void ancestorRemoved(AncestorEvent e) {}
});
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、JOptionPane.showConfirmDialogで表示するJTextFieldにデフォルトのフォーカスがあたるように設定しています。

  • 左上
    • デフォルト
int result = JOptionPane.showConfirmDialog(frame, textField, "Input Text",
                 JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
  textArea.setText(textField.getText());
}
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());
}
  • 左下
    • textFieldHierarchyListenerを追加し、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());
}
  • 右下
    • textFieldaddAncestorListenerを追加し、ancestorAddedが呼ばれたときに、textField.requestFocusInWindow();
    • Swing - Input focus

参考リンク

コメント