TITLE:JOptionPaneのデフォルトフォーカス
#navi(../)
RIGHT:Posted by [[terai]] at 2009-11-23
*JOptionPaneのデフォルトフォーカス [#p8003f6b]
JOptionPaneにデフォルトでフォーカスをもつコンポーネントを追加します。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#nd2fa665]
#code{{
textField4.addAncestorListener(new AncestorListener() {
  public void ancestorAdded(AncestorEvent event) {
    textField4.requestFocusInWindow();
  }
  public void ancestorMoved(AncestorEvent event) {}
  public void ancestorRemoved(AncestorEvent event) {}
});
}}

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

-左上
-- デフォルト
-右上
-- JOptionPane#createDialog(...)でJDialogを取得し、WindowListener#windowOpenedで、textField.requestFocusInWindow()
-- [[Windowを開いたときのフォーカスを指定>Swing/DefaultFocus]]など
-左下
-- textFieldにHierarchyListenerを追加し、hierarchyChangedが呼ばれたときに、textField.requestFocusInWindow()
-右下
-- textFieldにaddAncestorListenerを追加し、ancestorAddedが呼ばれたときに、textField.requestFocusInWindow()
-- [[Swing - Input focus>http://forums.sun.com/thread.jspa?threadID=777887]]

**参考リンク [#u3c4a8af]
- [[Windowを開いたときのフォーカスを指定>Swing/DefaultFocus]]など
- [[Swing - Input focus>http://forums.sun.com/thread.jspa?threadID=777887]]

**コメント [#nef3f20f]
#comment