Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么我不能将组件从JFrame中取出?_Java_Swing - Fatal编程技术网

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

Java 为什么我不能将组件从JFrame中取出?,java,swing,Java,Swing,我用我需要的一些附加功能扩展了JPanel类,然后创建了一个类似这样的实例: CustomPanel pan = new CustomPanel(); 然后,我将其添加到我的框架中: frame.getContentPane().add(pan); 然后我需要将面板从框架上取下,我这样做: for (Component c : frame.getComponents()) { if(c instanceof CustomPanel) { System.out.

我用我需要的一些附加功能扩展了JPanel类,然后创建了一个类似这样的实例:

CustomPanel pan = new CustomPanel();
然后,我将其添加到我的框架中:

frame.getContentPane().add(pan);
然后我需要将面板从框架上取下,我这样做:

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

但它在内存中不是作为CustomPanel存在的,而是作为JPanel存在的,这是为什么?

据我所知,JFrame包含一个JPanel,当您使用getContentPane.addpan将自定义面板添加到JFrame的JPanel时,实际上是在将自定义面板添加到JFrame的JPanel。我猜您必须调用frame.getContentPane.getComponents;迭代JFrame面板中包含的组件。

您的for应为:

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

您没有将面板添加到框架中,而是将其添加到内容窗格中。

+1有关JFrame结构的更详细信息,请参阅。-1,此建议是在前面提出的。没有必要在论坛上重复回答。