tags:

views:

197

answers:

3

Why this code never prints "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();
    }
}
A: 

I would guess that it's called when the visibility state of the actual object changes. in this case, you change the visibility of the Frame, not of the Panel. (by default, Frame starts hidden, but panels are visible) try to add the listener to the frame.

Omry
yes, that is right i re-read the api doc. Thank you.
PeterMmm
A: 

From Java Tutorials

The component-hidden and component-shown events occur only as the result of calls to a Component 's setVisible method. For example, a window might be miniaturized into an icon (iconified) without a component-hidden event being fired.

Carlos Tasada
+1  A: 

AWT's definition of "visible" may be a bit counter-intuitive. From the Javadoc of java.awt.Component#isVisible:

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

According to 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());

anywhere before you call f.setVisible(true). In that sense, the visibility is not changed when displaying the frame and hence componentShown(..) is not called.