How to catch an event when a JPanel is created ?

This is what I do (pseudocode):

MyJPanel j = new MyJPanel()

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:


if I have the following inside MyJPanel:

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

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

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?
rakhareAuthor Commented:
How can I add more points to this thread?
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()).
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.