developer tip

Java / Swing : JPanel 내부에서 Window / JFrame 가져 오기

optionbox 2020. 11. 3. 07:57
반응형

Java / Swing : JPanel 내부에서 Window / JFrame 가져 오기


JPanel이있는 JFrame을 어떻게 구할 수 있습니까?

내 현재 해결책은 창을 찾을 때까지 패널에 부모 (등)를 요청하는 것입니다.

Container parent = this; // this is a JPanel
do {
    parent = parent.getParent();
} while (!(parent instanceof Window) && parent != null);
if (parent != null) {
    // found a parent Window
}

더 우아한 방법이 있습니까, 표준 라이브러리의 방법이 될 수 있습니까?


SwingUtilities.getWindowAncestor(...)최상위 유형으로 캐스트 할 수있는 Window를 반환하는 메서드를 사용할 수 있습니다 .

JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);

SwingUtilities동일한 기능을 제공하는 두 가지 직접적이고 다른 방법이 있습니다 (Javadoc에 언급 됨). 그들은 반환 java.awt.Window되지만 패널을에 추가 한 경우 JFrame안전하게 캐스트 할 수 있습니다 JFrame.

직접적이고 가장 간단한 2 가지 방법 :

JFrame f1 = (JFrame) SwingUtilities.windowForComponent(comp);
JFrame f2 = (JFrame) SwingUtilities.getWindowAncestor(comp);

완전성을 위해 몇 가지 다른 방법 :

JFrame f3 = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, comp);
JFrame f4 = (JFrame) SwingUtilities.getRoot(comp);
JFrame f5 = (JFrame) SwingUtilities.getRootPane(comp).getParent();

JFrame frame = (JFrame)SwingUtilities.getRoot(x);

다른 해설자들이 이미 언급했듯이 단순히으로 캐스팅하는 것은 일반적으로 유효하지 않습니다 JFrame. 그것은 대부분의 특별한 경우에서 작동하지만 유일한 정답은 https://stackoverflow.com/a/25137298/1184842의f3 icza입니다.

JFrame f3 = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, comp);

이것은 유효하고 안전한 캐스트이며 다른 모든 답변만큼 간단하기 때문입니다.

참고 URL : https://stackoverflow.com/questions/9650874/java-swing-obtain-window-jframe-from-inside-a-jpanel

반응형