Why / when is the ComponentListener.componentShown () component called?

Why does this code never print "Hello2"?

public class Test4 {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        JPanel p = new JPanel();
        f.getContentPane().add(p);

        JLabel x = new JLabel("Hello");
        p.add(x);

        p.addComponentListener(new ComponentListener() {

            public void componentResized(ComponentEvent arg0) {
                 System.err.println("Hello1");
            }

            public void componentMoved(ComponentEvent arg0) {
            }

            public void componentShown(ComponentEvent arg0) {
                System.err.println("Hello2");
            }

            public void componentHidden(ComponentEvent arg0) {
            }
        });

        f.setVisible(true);
        f.pack();
    }
}
+3
source share
3 answers

I would suggest that it caused when the visibility state of the actual object changed. in this case, you change the visibility of the frame, not the panel. (by default, Frame starts to hide, but panels are visible) try adding a listener to the frame.

+3
source

The definition of AWT "visible" may be a bit controversial. From Javadoc java.awt.Component # isVisible:

"Components are initially visible, with the exception of top level components such as
 Frame objects."

In accordance with this description p is already visible before you add the ComponentListener. In fact, you can verify this if you insert a

System.out.println(p.getVisible());

, f.setVisible(true). , , , componentShown (..) .

+2

From Java Tutorials

The component is hidden and the events displayed by the components occur only as a result of calls to the component in the setVisible way. For example, a window can be miniaturized into an icon (indicated) without an event hidden by the component.

0
source

Source: https://habr.com/ru/post/1717839/


All Articles