Tomás Dornas Perone Tomás Dornas Perone - 9 days ago 5
Java Question

Thread Run not working properly

I made a simple Java program that uses a Thread object to move a square around a JPanel. The square moves to a random position, changes its color and the JPanel changes its background color. And then the thread sleeps for 1000 ms. But then I added one more line of code that adds +1 to a JLabel and the square stopped moving (while the score was working and adding +1).

Here is the code:

@Override
public void run() {

Random random = new Random();

int width = 0;
int height = 0;

while(true) {

width = random.nextInt(area.getSize().width) + 1;
height = random.nextInt(area.getSize().height) + 1;

width -= ((width - 45) > 0) ? 45 : 0;
height -= ((height - 45) > 0) ? 45 : 0;

this.square.setLocation(width, height);
this.square.setIcon(new ImageIcon(getClass().getResource("/img/square" + (random.nextInt(4) + 1) + ".png")));
this.area.setBackground(new Color(random.nextInt(255) + 1, random.nextInt(255) + 1, random.nextInt(255) + 1));

//The following line works, but the setLocation method stops working.

this.score.setText(Integer.toString(Integer.parseInt(this.score.getText()) + 1));

try {

sleep(1000);

} catch (InterruptedException ex) {

Logger.getLogger(RunThread.class.getName()).log(Level.SEVERE, null, ex);

}

}

}


Any ideas?

Thanks.

Edit: this is how I create a Thread...

public Click() {

initComponents();
pack();
setLocationRelativeTo(null);
setVisible(true);

RunThread run = new RunThread(jLabel1, jLabel2, jPanel1);
run.run();

}

Answer

invoke the run() method in

Which is wrong. That is not how to use a Thread. If you invoke the run() method then it is just treated like any other method and you are not using a Thread. Therefore, whenever you use Thread.Sleep(...) you are causing the Event Dispatch Thread(EDT) to sleep which means the GUI can't repaint itself.

To use a Thread. you need to invoke the start() method on the Thead, so the code should be:

run.start();