【发布时间】:2015-11-20 20:06:24
【问题描述】:
我刚开始学习 GUI 和 Swing,并决定编写一个我在教科书中找到的程序来显示一个彩色矩形,让它在屏幕上看起来像缩小了一样。
以下是我编写的代码,我的问题是矩形显示在屏幕上,但不是每 50 毫秒重新绘制为更小的尺寸。谁能指出我在哪里出错了?
非常感谢
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);
}
}
}
【问题讨论】:
-
您是否进行了任何基本调试?您是否在您的绘制方法中添加了一条语句以查看它是否被调用?你显示 x/y 的值了吗?
标签: java swing user-interface paintcomponent repaint