Problems repainting in a JPanel Runnable
I am writing a program that开发者_高级运维 will play a song and have a JPanel displaying images during it. The song plays fine, the first image is drawn (I assume from the initial call to paintComponent) but somehow the repaint() doesn't seem to be getting called. I could really use an extra set of eyes. I have the code below for the JPanel class that will be displaying the images. Thanks so much!
class pictures extends JPanel implements Runnable {
private ImageIcon images[];
private Thread imagerunner;
private int currentImage;
pictures() {
super();
imagerunner = new Thread(this);
images = new ImageIcon[6];
imagerunner = new Thread(this);
images[0] = new ImageIcon("pic1.jpg");
images[1] = new ImageIcon("pic2.jpg");
images[2] = new ImageIcon("pic3.jpg");
images[3] = new ImageIcon("pic4.jpg");
images[4] = new ImageIcon("pic5.jpg");
images[5] = new ImageIcon("pic6.jpg");
currentImage = 0;
}
public void run() {
int i = 0;
System.out.println("starting pics");
while( i < 100 ) {
System.out.println("about to repaint()");
this.repaint();
System.out.println( "image: " + currentImage );
waiting( 2000 );
currentImage++;
}
System.out.println("done");
}
public void paintComponent( Graphics g ) {
super.paintComponent( g );
System.out.println("repainting");
images[ currentImage ].paintIcon(this,g,0,0);
}
public static void waiting (int n) {
long t0, t1;
t0 = System.currentTimeMillis();
do{
t1 = System.currentTimeMillis();
}
while (t1 - t0 < n);
}
}
- You never start the thread
imagerunner
. - It is assigned twice (for no reason).
- You can't modify GUI from another thread. Use Swing utilities for that.
The waiting()
method seems to be blocking the EDT. It would be better to use a Swing Timer
to schedule the updates.
You would need to do the following:
1) Actually create an instance to run. 2) You will need to invoke repaint() regularly in order to get your display to repaint.
Hope it helps. Cheers!
精彩评论