1

jframeに存在するjbuttonの数をカウント/取得しようとしているこのコードがあります

jframeに7つのjbuttonと2つのjtextフィールドがありますが、出力は1になります

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

案内してもらえますか

4

4 に答える 4

2

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++;
}
于 2013-09-11T14:48:59.963 に答える
1

最初の行を変更してみてください:

Component c = (your JFrame object);
于 2013-09-11T14:45:00.177 に答える