TITLE:WindowAncestor(親ウィンドウ)の取得
#navi(../)
*WindowAncestor(親ウィンドウ)の取得 [#i3faa33c]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2005-05-09~
更新日:&lastmod;

#contents

**概要 [#a8e4cc0a]
SwingUtilities.getWindowAncestor()などで、親ウィンドウを取得します。

#screenshot

**サンプルコード [#vee7c80a]
#code{{
 JButton button = new JButton(new AbstractAction("フレームのタイトルを表示") {
   public void actionPerformed(ActionEvent ae) {
     final JButton btn  = (JButton)ae.getSource();
     final JFrame frame = (JFrame)SwingUtilities.getWindowAncestor(btn);
     //final JFrame frame = (JFrame)JOptionPane.getFrameForComponent(btn);
     SwingUtilities.invokeLater(new Runnable() {
       public void run() {
         JOptionPane.showMessageDialog(frame,
                     "親フレームのタイトル: "+frame.getTitle(),
                     "タイトル", JOptionPane.INFORMATION_MESSAGE);
       }
     });
   }
 });
}}
-&jnlp;
-&jar;
-&zip;

**解説 [#dec5efc1]
自分(コンポーネント)の最初の上位ウィンドウ(親ウィンドウ)を取得します。

SwingUtilities.getWindowAncestor、SwingUtilities.getRootメソッドを使うとjava.awt.Windowが、JOptionPane.getFrameForComponentメソッドを使うとjava.awt.Frameが返されます。

//**参考リンク
**コメント [#td33ce56]
- JComponent#getTopLevelAncestor()でもほぼ同じ内容が取得できるような感じですね(自分自身からスタートするか、親からスタートするかの違いはあるようですが)。ただ、この場合、Windowの他にAppletが戻される場合もあるようですが。 -- [[syo]] &new{2006-08-24 (木) 17:07:25};
- 補足ありがとうございます。WindowかAppletか気にする必要が無いのは便利そうですね。 -- [[terai]] &new{2006-08-25 (金) 12:46:43};

#comment