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:
But how?
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.
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