• category: swing folder: WindowAncestor title: WindowAncestor(親ウィンドウ)の取得 tags: [JFrame, Window] author: aterai pubdate: 2005-05-09 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()などで、親ウィンドウを取得します。

サンプルコード

サンプルコード

#spandel
JButton button = new JButton(new AbstractAction("フレームのタイトルを表示") {
#spanend
  @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);
#spanadd
JButton button = new JButton("show frame title");
#spanend
#spanadd
button.addActionListener(e -> {
#spanend
  // Container w = ((JComponent) e.getSource()).getTopLevelAncestor();
  Window w = SwingUtilities.getWindowAncestor((Component) e.getSource());
  // Frame frame = JOptionPane.getFrameForComponent((Component) e.getSource());
  if (w instanceof Frame) {
    Frame frame = (Frame) w;
    String msg = "parentFrame.getTitle(): " + frame.getTitle();
    JOptionPane.showMessageDialog(
        frame, msg, "title", JOptionPane.INFORMATION_MESSAGE);
  }
#spandel
}));
#spanend
#spanadd
});
#spanend
View in GitHub: Java, Kotlin

解説

解説

自分(コンポーネント)の最初の上位ウィンドウ(親ウィンドウ)を取得します。
  • SwingUtilities.getRoot(Component c)
    • Windowが無い場合はnullが返る
    • 引数のComponent自体がWindowの場合そのWindowのオーナーWindowが返る
      • オーナーWindownullの場合は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()
    • 自身の親コンテナ(java.awt.Windowまたはjava.awt.Applet)が返る
    • 親コンテナが無い場合は、null
      • 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から呼ばれた場合はそのまま自身が返る
    • 下のコメント参照

参考リンク

参考リンク

コメント

コメント