我有这段代码,我试图通过它来计算/获取 jframe 上存在的 jbutton 的数量
我在 jframe 上有 7 个 jbutton 和 2 个 jtext 字段,但输出为 1
Component c=this;
Container container = (Container) c;
int x = container.getComponentCount();
System.out.println(x);
我能得到一些指导吗
最佳答案
获取 JFrame 中的所有组件(提示:使用递归完成 here )。
public static List<Component> getAllComponents(final Container c) {
Component[] comps = c.getComponents();
List<Component> compList = new ArrayList<Component>();
for (Component comp : comps) {
compList.add(comp);
if (comp instanceof Container) {
compList.addAll(getAllComponents((Container) comp));
}
}
return compList;
}
然后测试是 jbutton 的组件。
int count =0;
for(Component c : getAllComponents(container)){
if(c instanceof JButton) count++;
}
关于java - 如何获取 jframe 上存在的 jbutton 的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18744251/