Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all elements inside a JFrame?

Tags:

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
}
like image 365
Renato Dinhani Avatar asked Jun 27 '11 16:06

Renato Dinhani


People also ask

What is content pane in JFrame?

JFrames have a content pane, which holds the components. These components are sized and positioned by the layout manager when JFrame's pack() is called. Content pane border. There are several ways to handle the content pane, but most of them fail to provide one basic requirement -- ability to set a border.

How do I view a JFrame?

A JFrame is like a Window with border, title, and buttons. We can implement most of the java swing applications using JFrame. By default, a JFrame can be displayed at the top-left position of a screen. We can display the center position of JFrame using the setLocationRelativeTo() method of Window class.

What does JFrame setVisible do?

The setVisible(true) method makes the frame appear on the screen. If you forget to do this, the frame object will exist as an object in memory, but no picture will appear on the screen.


2 Answers

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.

like image 127
aioobe Avatar answered Oct 05 '22 04:10

aioobe


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())    
like image 24
toto2 Avatar answered Oct 05 '22 04:10

toto2