View Single Post
  #1 (permalink)  
Old 08-15-2007, 06:02 PM
rjevans2000 rjevans2000 is offline
Member
 
Join Date: Aug 2007
Posts: 3
rjevans2000 is on a distinguished road
Repaint fails when using threads
Hi, I'm trying to get to grips with threads and am creating a test application that carries out several tasks simultaneously. My problem is that when using a thread, the repaint() method doesn't seem to update the panel that I would expect it to. Below is the fragment of code in question:

class ColourPanel extends JPanel implements Runnable {

public void run() {
try {
for (int i=0;i<100000;i++) {

randomNumber = Math.random();
if ((randomNumber >= 0) && (randomNumber < 0.25))
setBackground(Color.RED);
if ((randomNumber >= 0.25) && (randomNumber < 0.5))
setBackground(Color.BLUE);
if ((randomNumber >= 0.5) && (randomNumber < 0.75))
setBackground(Color.MAGENTA);
if ((randomNumber >= 0.75) && (randomNumber <= 1))
setBackground(Color.ORANGE);

repaint();
setVisible(true);
Thread.sleep(200);
}
}
catch (InterruptedException e) {
}
}

public ColourPanel() {

setLayout(new BorderLayout());

colourButton = new JButton("Change Background");
add(colourButton, BorderLayout.SOUTH);

colourButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {

Runnable q = new ColourPanel();
Thread s = new Thread(q);
s.start();

}
});
}

private JButton colourButton;
private double randomNumber;

}

I would expect the repaint() method to update the panel with the new background colour. However, this does not work and I can't see why. I have tried calling getParent().repaint() and getRootPane().repaint() but these also don't work. Am I barking up the wrong tree? Any help would be greatly appreciated!
Reply With Quote
Sponsored Links