I'm trying to color something in my program, but because the coloring proccess(repaint) is in a thread, the function thread.join() causes the recolor method to pause.
I want the repaint method to run inside the thread, but the whole code to wait until the global recoloring thread has finished its job.
I noticed that if I delete the ActionListener it works well, but I want the animation to work with the click of one of the buttons
Edit:
public class Main {
static Button [][] matrixButtons = new Button[7][2];
protected static Image imgRed;
protected static Image imgFreeSpace;
public Main()
{
File f1= new File("Images/free_cell.png");
File f2= new File("Images/player_one.png");
try {
imgFreeSpace = ImageIO.read(f1).getScaledInstance(90, 90, Image.SCALE_SMOOTH);
} catch (IOException e) {
e.printStackTrace();
}
try {
imgRed = ImageIO.read(f2).getScaledInstance(90, 90, Image.SCALE_SMOOTH);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JFrame jFrame = new JFrame();
GridLayout gridLayout = new GridLayout(7,1);
JPanel jPanel = new JPanel(gridLayout);
jFrame.add(jPanel,BorderLayout.CENTER);
for(int i = 0; i < 7; i++)
{
for (int j = 0; j < 2; j++) {
matrixButtons[i][j] = new Button(imgFreeSpace);
matrixButtons[i][j].setPreferredSize(new Dimension(90, 90));
matrixButtons[i][j].addActionListener(new AL(j,imgRed));
jPanel.add(matrixButtons[i][j]);
}
}
jFrame.pack();
jFrame.setVisible(true);
}
public static void main(String[] args){
new Main();
}
class AL implements ActionListener {
protected int col;
protected Image image;
public AL(int col,Image image) {
this.col = col;
this.image = image;
}
public void actionPerformed(ActionEvent e) {
animate(1, image);
}
}
public static void animate(int column, Image image) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
Image freeCellImage = imgFreeSpace;
for (int i = 0; i < 7; i++) {
matrixButtons[i][column].setImage(image);
matrixButtons[i][column].repaint();
Thread.sleep(100);
if (i != 7) {
matrixButtons[i][column].setImage(freeCellImage);
matrixButtons[i][column].repaint();
}
}
} catch (InterruptedException ex) {
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test");
}
}
Button class:
public class Button extends JButton {
private Image image;
public Button(Image image) {
this.image = image;
}
public void setImage(Image image) {
this.image = image;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}