• category: swing folder: WindowAncestor title: WindowAncestor(親ウィンドウ)の取得 tags: [JFrame, Window] author: aterai pubdate: 2005-05-09T21:28:35+09:00 description: SwingUtilities.getWindowAncestor()などで、親ウィンドウを取得します。 image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTWr-a0yaI/AAAAAAAAApo/Wm-nQMxDh4s/s800/WindowAncestor.png

概要

SwingUtilities.getWindowAncestor()などで、親ウィンドウを取得します。

サンプルコード

JButton button = new JButton(new AbstractAction("フレームのタイトルを表示") {
  @Override public void actionPerformed(ActionEvent e) {
    JButton btn  = (JButton) e.getSource();
    JFrame f = (JFrame) SwingUtilities.getWindowAncestor(btn);
    //JFrame f = (JFrame) btn.getTopLevelAncestor();
    //JFrame f = (JFrame) JOptionPane.getFrameForComponent(btn);
    JOptionPane.showMessageDialog(f, "parentFrame.getTitle(): " + f.getTitle(),
                                  "title", JOptionPane.INFORMATION_MESSAGE);
  }
}));
View in GitHub: Java, Kotlin

解説

自分(コンポーネント)の最初の上位ウィンドウ(親ウィンドウ)を取得します。

  • SwingUtilities.getWindowAncestor(Component c)
    • SwingUtilities.windowForComponent(Component c)は、このgetWindowAncestorをラップしただけのメソッド
    • 親のjava.awt.Windowが返る
    • Windowが無い場合は、nullが返る
    • 引数のComponent自体がWindowの場合、そのWindowのオーナウィンドウが返る
      • オーナウィンドウがnullの場合は、nullが返る
  • SwingUtilities.getRoot(Component c)
    • 親のComponent(java.awt.Windowまたはjava.awt.Applet)が返る
      • Windowの場合は、c.getParent()で見つかる最初の上位Windowオブジェクトだが、Appletの場合は、JComponent#getTopLevelAncestor()とは異なり、最後の上位Appletオブジェクト
    • どちらも存在しない場合は、null
    • 引数のComponent自体がWindowの場合は、そのまま自身が返る
  • JComponent#getTopLevelAncestor()
    • 自身の親Container(java.awt.Windowまたはjava.awt.Applet)が返る
    • Containerが無い場合は、null
    • java.awt.Windowまたはjava.awt.Appletから呼ばれた場合は、そのまま自身が返る
    • 下のコメント参照

参考リンク

コメント