john
john

Reputation: 51

Java Swing revalidate() and repaint() problem

I have a small java desktop application that needs to be able to add and remove fields dynamically by clicking "+" and "-" buttons respectively. I have gotten this to work by calling revalidate() and then repaint() on all the parent containers all the way up to the JFrame in the ActionListener.

This seemed to have done the trick, but occasionally it doesn't work and the JPanels don't resize correctly. This happens infrequently and seemingly at random and lead me to believe it might be a concurrency issue. I have tried launching the parent container from the event dispatch thread but this hasn't solved the problem.

Is this actually a concurrency issue or am I barking up the wrong tree? Anyone have any idea what is going on and how it can be solved?

Much appreciated

-SwingNoob

Upvotes: 5

Views: 5569

Answers (2)

user330315
user330315

Reputation:

Launching the container from the AWT/EDT thread is not enough.

You need to execute every layout change to the container on the AWT/EDT thread.

So if you make sure your add and remove are done that way, revalidate() or repaint() should not be necessary.

Upvotes: 2

mKorbel
mKorbel

Reputation: 109813

that isn't answer to OP's question nice example, OP's problem is maybe about LayoutManager and something unknow in OP's code

1/ if you adds a new JComponent to the Container then you have to call

validate();
repaint(); //lay with LayoutManager required that 

2/ if removes and then adds a JComponents from/to the Container then you have to call

revalidate();
repaint(); // lay with LayoutManager required that 

3/ looks like as revalidate covered validate too,

Upvotes: 5

Related Questions