jframeに存在するjbuttonの数をカウント/取得しようとしているこのコードがあります
jframeに7つのjbuttonと2つのjtextフィールドがありますが、出力は1になります
Component c=this;
Container container = (Container) c;
int x = container.getComponentCount();
System.out.println(x);
案内してもらえますか
JFrame 内のすべてのコンポーネントを取得します (ヒント:ここで行ったように再帰を使用します)。
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;
}
次に、jbuttons であるコンポーネントをテストします。
int count =0;
for(Component c : getAllComponents(container)){
if(c instanceof JButton) count++;
}
最初の行を変更してみてください:
Component c = (your JFrame object);