Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/320.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上存在的jbutton数_Java_Swing - Fatal编程技术网

Java 如何获取jframe上存在的jbutton数

Java 如何获取jframe上存在的jbutton数,java,swing,Java,Swing,我有一段代码,我试图通过它来计算/获取jframe上出现的JButton的数量 我在jframe上有7个JButton和2个jtext字段,但输出是1 Component c=this; Container container = (Container) c; int x = container.getComponentCount(); System.out.println(x); 我能得到一些指导吗?试着改变你的第一行: Component c = (your JFrame object);

我有一段代码,我试图通过它来计算/获取jframe上出现的JButton的数量

我在jframe上有7个JButton和2个jtext字段,但输出是1

Component c=this;
Container container = (Container) c;
int x = container.getComponentCount();
System.out.println(x);

我能得到一些指导吗?

试着改变你的第一行:

Component c = (your JFrame object);

尝试更改第一行:

Component c = (your JFrame object);

您可以使用Darryl来递归搜索容器中的组件。

您可以使用Darryl来递归搜索容器中的组件。

获取JFrame中的所有组件(提示:按原样使用递归)


获取JFrame中的所有组件(提示:按原样使用递归)


听起来您最好是计算层次结构中的组件,而不是单个组件,例如:

public static int countSubComponentsOfType(Container container, Class<? extends Component> type){
    int count = 0;
    for(Component component : container.getComponents()){
        if(type.isInstance(component)) count++;
        if(component instanceof Container) 
            count += countSubComponentsOfType((Container)component, type);
    }
    return count;
}

这是因为JFrame总是只包含一个子组件,即JRootPane。添加到JFrame的任何内容都会添加到根窗格。

听起来您最好计算层次结构中的组件,而不是单个组件,例如:

public static int countSubComponentsOfType(Container container, Class<? extends Component> type){
    int count = 0;
    for(Component component : container.getComponents()){
        if(type.isInstance(component)) count++;
        if(component instanceof Container) 
            count += countSubComponentsOfType((Container)component, type);
    }
    return count;
}

这是因为JFrame总是只包含一个子组件,即JRootPane。添加到JFrame的任何内容都会添加到根窗格。

容器中可能只有一个
JPanel
——这就是
getComponentCount()
返回的内容。您应该在其上获得
JPanel
getComponentCount()
。您使用的是画布吗?查看此问题在您的情况下可能会有所帮助我将JFrame与JList一起使用,将JTextArea与Jbutton和Jtext Field一起使用可能容器中只有一个
JPanel
,这就是
getComponentCount()
返回的内容。您应该在其上获得
JPanel
getComponentCount()
。您使用的是画布吗?查看此问题可能对您的情况有所帮助我将JFrame与JList一起使用,将JTextArea与Jbutton和Jtext字段一起使用
frame.getRootPane().getComponentCount();