如何在侦听器内迭代JPanel的子组件

时间:2014-03-15 08:16:47

标签: java swing jpanel event-listener componentlistener

我在JPanel上放了一个“调整大小”的监听器。

当触发器被触发时,我想遍历该JPanel的所有子组件。

我知道如何使用“e.getComponent()”在监听器中获取JPanel组件,但是其中没有“getComponents()”来迭代。

我想通过“e”对象来达到它,而不是让“item”成为一个类变量。

有关详细信息,请参阅代码注释:

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

}

}

1 个答案:

答案 0 :(得分:3)

由于您将侦听器附加到JPanel,因此您可以转换事件的来源

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

投射后,您可以使用Container类API方法迭代子组件(getComponent( int )getComponentCount()getComponents