Friday Sep 29, 2006

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.

Friday Sep 22, 2006

Profiling Tips

Do you know what the Profiler calibration exactly is and what it is good for? Are you aware of the differences in your application behavior when being profiled? Do you know that some of application methods won't appear in collected results? And are you absolutely sure that you are able to get as much accurate results from the Profiler as possible?

If you are not absolutely sure about anything of the above, take a quick look at Profiling Tips in Profiler docs. You may find it a really useful reading.

About

A blog by NetBeans Profiler & VisualVM developers.

Search

Categories
Archives
« July 2015
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
31
 
       
Today