简体   繁体   English

为什么我不能将组件从JFrame中取出?

[英]Why can I not get my components back out of JFrame?

I have extended the JPanel class with some additional functionality I require, and I then created an instance of it like so: 我用一些我需要的附加功能扩展了JPanel类,然后创建了它的实例,如下所示:

CustomPanel pan = new CustomPanel();

I then add it to my to my frame: 然后,将其添加到我的框架中:

frame.getContentPane().add(pan);

I then need to the panel back off the frame, I do this like so: 然后,我需要使面板退回框架,就像这样:

for (Component c : frame.getComponents())
{
    if(c instanceof CustomPanel)
    {
        System.out.println("Should get here");
    }       
}

But it doesn't exist in memory as a CustomPanel, instead it exists as a JPanel, why is this? 但是它在内存中不作为CustomPanel存在,而是作为JPanel存在,为什么?

From what I understand, the JFrame contains a JPanel, when you add your custom Panel to the JFrame using getContentPane().add(pan), you're actually adding your custom panel to the JFrame's JPanel. 据我了解,JFrame包含一个JPanel,当使用getContentPane()。add(pan)将自定义面板添加到JFrame时,实际上是在将自定义面板添加到JFrame的JPanel中。 I'm guessing you'll have to call frame.getContentPane().getComponents(); 我猜你将不得不调用frame.getContentPane()。getComponents(); to iterate over the components contained in the JFrame's panel. 遍历JFrame面板中包含的组件。

Your for should read: 您的for应该阅读:

for (Component c : frame.getContentPane().getComponents())

You didn't add your Panel to the frame, you added it to the content pane. 您没有将面板添加到框架,而是将其添加到内容窗格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM