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
revalidate(): This method tells the layout manager to recalculate the layout that is necessary when adding components.
In Java Swing, we can change the paintComponent() method instead of paint() method as paint calls paintBorder(), paintComponent() and paintChildren() methods. We cannot call this method directly instead we can call repaint(). repaint(): This method cannot be overridden. It controls the update() -> paint() cycle.
repaint() in Java Applet Example The repaint () method causes the AWT runtime system to execute the update () method of the Component class which clears the window with the background color of the applet and then calls the paint () method.
JFrame. repaint() will repaint itself and its children. But since JFrame is the base, this will repaint every component within.
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With