ComponentListener vs. HierarchyListener

Did you ever need to tweak component properties immediately after it appears on the screen? It seems to be quite trivial task but it took me a while till I found the right way how to do it.

The problem was to obtain a notification that the component has been shown. I used java.awt.event.ComponentListener (ComponentAdapter) and its componentShown event - it worked quite fine but never reported the event for the very first time the component was shown.

    component.addComponentListener(new ComponentAdapter() {
      public void componentShown(ComponentEvent e) {
        System.out.println("Component shown");
      }
    });

What's the cause? The componentShown event is fired every time component's visibility - value of java.awt.Component.isVisible() - is changed. When the component is created, its isVisible() returns true, so no change happens when it's displayed for the first time.

The correct property I needed to listen on is java.awt.Component.isShowing(). Its value is false unless the component is really showing on the screen. But there didn't seem to be any appropriate listener - ComponentListener.componentShown() actually does "componentMadeVisible()", but where is the real "componentShown()" implemented?

After some time of googling I finally found a solution: java.awt.event.HierarchyListener. It has just one event hierarchyChanged which doesn't seem to be much useful, but all the magic is hidden in java.awt.event.HierarchyEvent which is passed to the method. Among other pure hierarchy-related stuff there is a SHOWING_CHANGED flag which "Indicates that the HIERARCHY_CHANGED event was generated due to a change in the showing state of the hierarchy". In other words it's a listener for Component.isShowing() property.

    component.addHierarchyListener(new HierarchyListener() {
      public void hierarchyChanged(HierarchyEvent e) {
        if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) 
          System.out.println("Component shown");
      }
    });

Now I was finally able to change anything about the component after it was shown for the first time.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

A blog by NetBeans Profiler & VisualVM developers.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today