Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

A continuation, suggested here, is a good choice for updating the GUI from multiple threads, but it may be difficult to correctly synchronize access to shared data.

Alternatively, use a javax.swing.Timer to periodically update a model that manages the properties of wolves and rabbits. A related example of objects moving on a grid is examined here. For greater flexibility, use the Model–View–Controller pattern, illustrated here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top