简体   繁体   中英

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

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,

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM