Swing/WindowAncestor のバックアップ(No.24)
- バックアップ一覧
 - 差分 を表示
 - 現在との差分 を表示
 - 現在との差分 - Visual を表示
 - ソース を表示
 - Swing/WindowAncestor へ行く。
  
- 1 (2005-09-02 (金) 21:28:35)
 - 2 (2005-09-30 (金) 16:31:37)
 - 3 (2006-02-27 (月) 16:37:17)
 - 4 (2006-08-24 (木) 17:07:25)
 - 5 (2006-08-25 (金) 12:46:43)
 - 6 (2007-05-04 (金) 03:29:20)
 - 7 (2007-12-11 (火) 14:11:52)
 - 8 (2008-05-09 (金) 14:34:28)
 - 9 (2011-03-20 (日) 16:58:24)
 - 10 (2012-03-13 (火) 20:58:15)
 - 11 (2013-03-30 (土) 21:01:15)
 - 12 (2013-10-15 (火) 17:36:02)
 - 13 (2015-02-09 (月) 17:22:52)
 - 14 (2015-06-05 (金) 17:16:52)
 - 15 (2015-12-22 (火) 15:31:00)
 - 16 (2016-03-29 (火) 18:42:44)
 - 17 (2016-08-18 (木) 12:44:25)
 - 18 (2017-04-04 (火) 14:13:45)
 - 19 (2017-04-07 (金) 13:51:51)
 - 20 (2017-10-06 (金) 14:54:33)
 - 21 (2019-04-10 (水) 13:45:03)
 - 22 (2021-01-20 (水) 18:23:06)
 - 23 (2023-08-25 (金) 13:56:29)
 - 24 (2025-01-03 (金) 08:57:02)
 - 25 (2025-01-03 (金) 09:01:23)
 - 26 (2025-01-03 (金) 09:02:38)
 - 27 (2025-01-03 (金) 09:03:21)
 - 28 (2025-01-03 (金) 09:04:02)
 - 29 (2025-06-19 (木) 12:41:37)
 - 30 (2025-06-19 (木) 12:43:47)
 
 
- category: swing
folder: WindowAncestor
title: WindowAncestor(親ウィンドウ)の取得
tags: [JFrame, Window]
author: aterai
pubdate: 2005-05-09T21:28:35+09:00
description: SwingUtilities.getWindowAncestor()などで、親ウィンドウを取得します。
image: 

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

Advertisement
サンプルコード
JButton button = new JButton("show frame title");
button.addActionListener(e -> {
  // 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);
  }
});
View in GitHub: Java, Kotlin解説
自分(コンポーネント)の最初の上位ウィンドウ(親ウィンドウ)を取得します。
- SwingUtilities.getWindowAncestor(Component c)
SwingUtilities.windowForComponent(Component c)は、このgetWindowAncestorをラップしただけのメソッド- 親の
java.awt.Windowが返る - 親
Windowが無い場合はnullが返る - 引数の
Component自体がWindowの場合そのWindowのオーナー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から呼ばれた場合はそのまま自身が返る- 下のコメント参照
 
 - 自身の親
 
- JOptionPane.getFrameForComponent(Component parentComponent)
- 親の
java.awt.Frameが返る - 有効な親
Frameが無い場合はJOptionPane.getRootFrame()で非表示にしているTookKit Privateなフレームが返る JOptionPane用?
 - 親の