我刚开始学习GUI的和Swing,并决定写一个程序我在一本教科书来显示彩色矩形,使它看起来像它在减小尺寸在屏幕上找到。的Java Swing动画的基本问题
下面是我写的代码,我的问题是,矩形在屏幕上显示,但不重新粉刷,以更小的尺寸每隔50ms。任何人都可以指出我哪里错了?
非常感谢
import javax.swing.*;
import java.awt.*;
public class Animate {
int x = 1;
int y = 1;
public static void main(String[] args){
Animate gui = new Animate();
gui.start();
}
public void start(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Rectangles rectangles = new Rectangles();
frame.getContentPane().add(rectangles);
frame.setSize(500,270);
frame.setVisible(true);
for(int i = 0; i < 100; i++,y++,x++){
x++;
rectangles.repaint();
try {
Thread.sleep(50);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
class Rectangles extends JPanel {
public void paintComponent(Graphics g){
g.setColor(Color.blue);
g.fillRect(x, y, 500-x*2, 250-y*2);
}
}
}
你做任何基本的调试?你有没有向你的paint方法添加一条语句来查看它是否被调用?你有没有显示x/y的值? – camickr