Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

10 threads painting on one JPanel

I've got some problems while learning threads in Java. The goal is to make a simulation that shows us how rabbits are running from wolves on some kind of board. Every wolf and every rabbit should be a thread. So I created a GUI in main method of Test class and created a new class that implements the Runnable interface. That's easy and logical I think. But now, how can I call the AddRabbit method from these threads? Because very thread should do mething like:

  1. Change its properties like place on the map
  2. Check other threads place on the map
  3. Paint itself on the panel

But how?

like image 783
ŁukaszG Avatar asked Jan 18 '26 10:01

ŁukaszG


1 Answers

Updating Swing components directly using multiple threads is not allowed--Swing is not threadsafe. There is a single Swing event queue that it processes, so if you have to update a JComponent in an existing thread, you will use the following code:

//You are currently in a separate thread that's calculating your rabbit positions
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        //Put in code to modify your Swing elements
    }
});

So every time you feel the need to update your GUI, then you can pass an instance of Runnable onto the Swing event queue using the SwingUtilities.invokeLater method, which it will process in its own thread.

like image 120
shimizu Avatar answered Jan 20 '26 04:01

shimizu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!