Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing revalidate() and repaint() problem

Tags:

java

swing

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

like image 205
john Avatar asked Jun 19 '11 22:06

john


People also ask

What does revalidate () do in Java?

revalidate(): This method tells the layout manager to recalculate the layout that is necessary when adding components.

How do you repaint a swing in Java?

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.

What is repaint in Java?

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.

What does JFrame repaint do?

JFrame. repaint() will repaint itself and its children. But since JFrame is the base, this will repaint every component within.


1 Answers

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,

like image 119
mKorbel Avatar answered Nov 02 '22 07:11

mKorbel