问题
I have this code to get all the elements I need and do some processing. The problem is I need to specify every panel I have to get the elements inside it.
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
I want to do something like this and get all the elements without need specefy all the panels names. How I do this. The code below don\'t get all the elements.
for (Component c : this.getComponents()) {
//processing
}
回答1:
You can write a recursive method and recurse on every container:
This site provides some sample code:
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;
}
If you only want the components of the immediate sub-components, you could limit the recursion depth to 2.
回答2:
Look at the doc for JFrame.
Everything you put in a JFrame
is actually put in a root pane contained in the frame.
for (Component c : this.getRootPane().getComponents())
回答3:
for (Component c : mainPanel.getComponents()) {
for (Component sc : ((JPanel) c).getComponents()) {
if (sc instanceof JTextField) {
//process
}
}
}
in my code, im just getting all instances of jtextfield. u can use same logic. this is just example of getting all sub-components from components you have taken. Hope it will help u out.
回答4:
If you want to find all components of a given type, then you can use this recursive method!
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());
}
and it can be used like this:
// 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);
来源:https://stackoverflow.com/questions/6495769/how-to-get-all-elements-inside-a-jframe