How to catch an event when a JPanel is created ?


This is what I do (pseudocode):

MyJPanel j = new MyJPanel()
somePanel.add(j);

I need something inside MyJPanel to catch the event of being created to adjust some items inside MyJPanel, like OnFormLoad in VB.  The constructor does not work since the UI elements seem to be created AFTER the constructor is created.

somePanel.validate() did not work.

The following works:

j.setVisible(false);
j.setVisible(true);

if I have the following inside MyJPanel:

        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

But it looks like a hack to me and I think there might be a standard way to do it.
rakhareAsked:
Who is Participating?
 
aozarovCommented:
What about overriding protected void paintComponent(Graphics g) in your JPanel class?
0
 
rakhareAuthor Commented:

BINGO !!
0
 
rakhareAuthor Commented:

But this has side effects.

1. I have several MyJPanels in JScrollPane. So when I scroll, paintComponent gets called. I can bypass it with a counter/flag.

2. There are new MyJPanels created in the non-visible portions of JScrollPane. For those, the above event is not caught. How do I catch that?
0
 
rakhareAuthor Commented:
How can I add more points to this thread?
0
 
aozarovCommented:
Yes, paintComponent will be called only on visible item each time the components needs to repaint itself (moved, resized,...)
That should be similar to componentShown,no? (I don't think componentShown will send event to a non visible component).
You can override the paintComponent (call super.paintComponent in it though) in the JScorllPange and then get all your MyJPanels from there (getComponents()).
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.