20

必要なすべての要素を取得し、いくつかの処理を行うためのこのコードがあります。問題は、内部の要素を取得する必要があるすべてのパネルを指定する必要があることです。

for (Component c : panCrawling.getComponents()) {
    //processing
}
for (Component c : panFile.getComponents()) {
    //processing
}
for (Component c : panThread.getComponents()) {
    //processing
}
for (Component c : panLog.getComponents()) {
    //processing
}
//continue to all panels

私はこのようなことをして、すべてのパネル名を指定する必要なくすべての要素を取得したいと考えています。これを行う方法。以下のコードは、すべての要素を取得するわけではありません。

for (Component c : this.getComponents()) {
    //processing
}
4

4 に答える 4

42

再帰メソッドを記述して、すべてのコンテナで再帰できます。

このサイトでは、いくつかのサンプル コードを提供しています。

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;
}

直接のサブコンポーネントのコンポーネントのみが必要な場合は、再帰の深さを 2 に制限できます。

于 2011-06-27T16:16:17.343 に答える
15

JFrameのドキュメントを見てください。に入れるものはすべて、JFrame実際にはフレームに含まれるルート ペインに入れられます。

for (Component c : this.getRootPane().getComponents())    
于 2011-06-27T16:21:15.227 に答える
0
            for (Component c : mainPanel.getComponents()) {
                for (Component sc : ((JPanel) c).getComponents()) {
                    if (sc instanceof JTextField) {
                        //process
                    }
                }
            }

私のコードでは、jtextfield のすべてのインスタンスを取得しています。同じロジックを使用できます。これは、取得したコンポーネントからすべてのサブコンポーネントを取得する例にすぎません。それがあなたを助けることを願っています。

于 2016-11-30T12:11:56.713 に答える
0

特定のタイプのすべてのコンポーネントを見つけたい場合は、この再帰的な方法を使用できます!

public static <T extends JComponent> List<T> findComponents(
    final Container container,
    final Class<T> componentType
) {
    return Stream.concat(
        Arrays.stream(container.getComponents())
            .filter(componentType::isInstance)
            .map(componentType::cast),
        Arrays.stream(container.getComponents())
            .filter(Container.class::isInstance)
            .map(Container.class::cast)
            .flatMap(c -> findComponents(c, componentType).stream())
    ).collect(Collectors.toList());
}

次のように使用できます。

// list all components:
findComponents(container, JComponent.class).stream().forEach(System.out::println);
// list components that are buttons
findComponents(container, JButton.class).stream().forEach(System.out::println);
于 2016-12-09T16:25:56.297 に答える