class DrawIma extends JPanel{
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i=0;i<20;i++){
for (int j=0;j<20;j++) {
g.drawImage(BuArr[i*20+j], 20*i, 20*j, 20, 20, null);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
In this part, BuArr are the 400 blocks divided from a BufferedImage, now i want them to be draw one by one, but the method can not draw the blocks separately, how can i do this?
Swing is single thread and not thread safe.
This means that you should not perform any long running or blocking (
Thread.sleep) operations within the IU thread (the Event Dispatching Thread). It also means that you can not update, modify or create UI elements outside of the EDT context.Instead, use a Swing
Timerto generate a repeated callback at a specified interval and render the portions of the image to something like aBufferedImage, which you can the paint to the component via itspaintComponentmethod...See Concurrency in Swing and How to use Swing Timers for more details
Because it was a good time waster
This generates a
ListofRectangleswhich represent the individual blocks I want to paint, I then randomise theListand run theTimer, picking the top mostRectangleoff theListand usingBufferedImage#getSubImageto draw it from the master to the buffer, which gets painted to the screen...