Eg. – take the class
import java.awt.Color;
import java.util.Random;
import javax.swing.JLabel;
public class flashThread implements Runnable {
private JLabel temp;
Thread thread;
Color randColor;
public flashThread(JLabel toFlash) {
temp = toFlash;
thread = new Thread(this);
}
public void run() {
Random r = new Random();
while (true) {
temp.setForeground(new Color(r.nextInt(246) + 10,
r.nextInt(246) + 10, r.nextInt(246) + 10));
String tempString = temp.getText();
temp.setText("");
try {
thread.sleep(r.nextInt(500));
} catch (InterruptedException e) {
}
temp.setText(tempString);
try {
thread.sleep(r.nextInt(500));
} catch (InterruptedException e) {
}
}
}
public void begin() {
thread.start();
}
}
If I added thread.start() in the constructor, when I create two objects of the flashThread, Only one of them flashes. However, If i remove then, add the begin() method and then call the begin method from the class that initialized both flashThread objects, they both flash.
Any Help – I’ve only just started to learn about threads.
Thanks in advance!
-Me
First of all please start your class name with a capital letter since this is convention in java.
It doesn’t matter if you start your thread in the constructor or in a method. One problem is that you access UI elements outside of the Event Dispatching Thread (EDT), which is the only one which is allowed to access, UI elements.
Use SwingUtilities.invokeLater instead. Furthermore invoke static methods like Thread#sleep on classes e.g.
Thread.sleep(1000);not on instances.So updating your code would look like: