public Ball() { super("Ball"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pane = new JPanel(); pane.setLayout(new GridLayout(1, 1, 15, 15)); ball = new BallPane(); pane.add(ball); setContentPane(pane); setSize(180, 145); show(); }
public static void main(String[] args) { new Ball(); } }class BallPane extends JPanel implements Runnable { Thread runner; int num = 100; int x = 0; int y = 0; int xi = 1; int yi = 1;
public BallPane() { runner = new Thread(this); runner.start(); }
这里有例子和代码
import java.awt.event.*;
import javax.swing.*;public class Ball extends JFrame
{
JPanel pane;
BallPane ball;
public Ball()
{
super("Ball");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pane = new JPanel();
pane.setLayout(new GridLayout(1, 1, 15, 15));
ball = new BallPane();
pane.add(ball);
setContentPane(pane);
setSize(180, 145);
show();
}
public static void main(String[] args)
{
new Ball();
}
}class BallPane extends JPanel implements Runnable
{
Thread runner;
int num = 100;
int x = 0;
int y = 0;
int xi = 1;
int yi = 1;
public BallPane()
{
runner = new Thread(this);
runner.start();
}
public void run()
{
while(true)
{
try
{
scroll();
repaint();
Thread.sleep(10);
} catch (InterruptedException e) {}
}
}
public void paintComponent(Graphics comp)
{
Graphics2D comp2D = (Graphics2D)comp;
comp2D.setColor(getBackground());
comp2D.fillRect(0, 0, getWidth(), getHeight());
if (num < Integer.MAX_VALUE)
{
comp2D.setColor(Color.decode("" + num));
comp2D.fillOval(x, y, 20, 20);
num += 1000;
}
else
{
num = 100;
}
}
public void scroll()
{
x += xi;
y += yi;
if((x==150) || (x==0))
{
xi = -xi;
}
if((y==100) || (y==0))
{
yi = -yi;
}
}
}你把在paintComponent里面的fillOval换成一个图片就可以了