java 用swing类做出的简单图形移动小程序
import javax.swing.*;
import java.awt.*;
public class SimpleCarton{
JFrame frame;
MyPanel panel;
int x = 50;
int y = 50;
public static void main(String[] args){
SimpleCarton sc = new SimpleCarton();
sc.go();
}
public void go(){
//initialize the frame layout
frame = new JFrame("Simple Carton");
panel = new MyPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.setSize(500, 500);
frame.setVisible(true);
//change the coordinate and repaint the figure
for(int i = 0;i < 250;i++){
x++;//the length of every step determines the moving speed
y++;//the length of every step determines the moving speed
panel.repaint();
try{
Thread.sleep(50); //program delay 50 milliseconds every time
}catch(Exception ex){ }
}
}
class MyPanel extends JPanel{
public void paintComponent(Graphics g){
//before each repaint,set background to be white so as to erase the last time imprint
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
//uese the new coordinate to repaint new figure
g.setColor(Color.orange);
g.fillOval(x, y,100, 100);
}
}
}
运行结果如图所示: