javaswingjpanelevent-listenercomponentlistener

How to iterate through sub-components of a JPanel inside a listener


I have put a "resize" listener on a JPanel.

When the listener is triggered, I want to iterate through all the sub-components of that JPanel.

I know how to get the JPanel component inside the listener with "e.getComponent()", but there is no "getComponents()" inside it to iterate over.

I want to reach it through the "e" object, not make "item" a class wide variable.

See the code comments for more details:

import java.awt.Color;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

public class BottomTest extends JFrame {

private static final long serialVersionUID = 1L;

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new BottomTest().setVisible(true);
        }
    });
}

public BottomTest() {

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("Test");
    setSize(1000, 700);
    setLocationRelativeTo(null);

    JPanel container = new JPanel();
    container.setBorder(new LineBorder(Color.RED, 1));
    container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
    add(container);

    JPanel item = new JPanel();
    item.setBorder(new LineBorder(Color.GREEN, 1));
    item.setLayout(new BoxLayout(item, BoxLayout.Y_AXIS));
    item.addComponentListener(new ComponentListener() {
        public void componentHidden(ComponentEvent arg0) {}
        public void componentMoved(ComponentEvent arg0) {}
        public void componentShown(ComponentEvent arg0) {}
        public void componentResized(ComponentEvent e) {

            //HOW CAN I ITERATE THROUGH THE SUB-COMPONENTS OF "ITEM" HERE?
            //I.E I WANT TOO SEE THE "TEXTPANE" COMPONENT HERE

            //System.out.println(e.getComponent());
            //THE ABOVE DOES NOT CONTAIN THE USUAL .GETCOMPONENTS()
        }           
    });
    container.add(item);

    JTextPane textPane = new JTextPane();
    textPane.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry.");
    item.add(textPane);

}

}

Solution

  • Since you attached the listener to a JPanel, you can cast the source of the event

    JPanel source = (JPanel) e.getComponent();
    

    Once you have cast it, you can use the Container class API methods to iterate over the child components (getComponent( int ), getComponentCount(), getComponents)