第一个java gui动画
使用x,y记录圆的位置
使用了for循环
内部进行sleep
x,y自增
刷新frame
import java.awt.*;
import javax.swing.*;
class MyAnimation extends Thread{
private JFrame frame = new JFrame();
private int x = 50;
private int y = 50;
public void start() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.getContentPane().add(BorderLayout.CENTER, new Mypanel());
frame.setVisible(true);
for (int i = 0; i < 500; i++) {
x++;
y++;
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
frame.repaint();
}
}
public static void main(String[] args) {
MyAnimation animation = new MyAnimation();
animation.start();
}
class Mypanel extends JPanel {
@Override
protected void paintComponent(Graphics graphics) {
Color color = new Color(100, 100, 100);
graphics.setColor(color);
graphics.fillOval(x, y, 100, 100);
}
}
}