呵呵,我写了一个,楼主可以参考一下,其实这种题目不难的。
/**
* This is a simple Java2D program.
* @author jellen
*/
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.*;
class Ball {
private int x = (int)(390 * Math.random()) + 21;
private int y = (int)(390 * Math.random()) + 21;
private static final int w = 30;
private static final int h = 30;
private int dx = 3;
private int dy = 3;
public void draw(Graphics2D g) {
g.fill(new Ellipse2D.Double(x, y, w, h));
}
public void move() {
x += dx;
y += dy;
if(x < 20) {
x = 20;
dx = -dx;
}
if(y < 20) {
y = 20;
dy = -dy;
}
if(x + w >= 420) {
x = 420 - w;
dx = -dx;
}
if(y + h >= 420) {
y = 420 - h;
dy = -dy;
}
}
}
class MyPanel extends JPanel implements Runnable {
private Rectangle2D rect = new Rectangle2D.Double(20, 20, 400, 400);
private Ball ball = new Ball();
public MyPanel() {
Thread t = new Thread(this);
t.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.BLUE);
g2.fill(rect);
g2.setColor(Color.RED);
ball.draw(g2);
}
public void run() {
while(true) {
try {
ball.move();
Thread.sleep(5);
repaint();
} catch(InterruptedException e) {
}
}
}
}
public class Move {
public static void main(String[] args) {
JFrame me = new JFrame("Move Test");
me.setSize(450, 470);
me.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
me.setResizable(false);
me.getContentPane().add(new MyPanel());
me.setVisible(true);
}
}