Skip to content
Advertisement

Java move GUI panel While loop

I have a panel. I want to move the panel, inside a while loop, to the left and then to the right, after pressing a button and until a certain condition is met. But for this question let’s say continuously. After it finishes an iteration, it doesn’t move left or right. I used repaint() and Thread.sleep(1000) but nothing shows up. Please help me

JavaScript

Advertisement

Answer

We meet again!

I managed to implement the moving JPanel using a Swing timer.

Since you want to move the JPanel, you need to place it in a parent container that is large enough to allow the JPanel to be placed in different locations within it. You also need to use a null layout manager because most layout managers will ignore calls to method setLocation().

More explanations after the code.

JavaScript

Swing is event driven. Events are added to a queue and then read off the queue and performed. Setting the location of a JPanel is an event. Calling events in a loop just floods the queue with events and some may be lost. That’s why there is the Swing Timer class. In the above code, every half second I change the location of jPanel1.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement