你好,我正在研究关于2D图形,并希望让这样的事情 http://i60.tinypic.com/71tm37.png的Java JPanel的颜色没有出现
我对JPanel的框架和声明代码是这样的:
public class Animation extends JPanel {
private ArrayList<BouncingCircle> circles;
Animation() {
this.setSize(320, 240);
this.setOpaque(true);
this.setBackground(new java.awt.Color(102, 255, 102));
circles = new ArrayList<BouncingCircle>();
}
public void paint(Graphics g) {
Image dbImg = createImage(getWidth(), getHeight());
Graphics dbg = dbImg.getGraphics();
draw(dbg);
g.drawImage(dbImg, 0, 0, this);
}
public void draw(Graphics g) {
for (int i = 0; i < circles.size(); i++) {
BouncingCircle bc = circles.get(i);
bc.draw(g);
}
repaint();
}
private void addCircle() {
BouncingCircle bc = new BouncingCircle();
circles.add(bc);
Thread t = new Thread(bc);
t.start();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Game");
frame.setVisible(true);
frame.setSize(320,240);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Animation a = new Animation();
frame.getContentPane().add(a);
for (int i = 0; i < 5; i++) {
a.addCircle();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.err.println("Error: Thread Interrupted.");
}
}
}
的BouncingCircle这里类:
public class BouncingCircle implements Runnable {
private int x;
private int y;
private int xVelocity;
private int yVelocity;
BouncingCircle() {
x = 0;
y = 0;
xVelocity = 2;
yVelocity = 2;
}
public void run() {
while (true) {
move();
try {
Thread.sleep(5);
} catch (InterruptedException ex) {
System.err.println("Error: Thread Interrupted.");
}
}
}
private void move() {
x += xVelocity;
y += yVelocity;
if (x < 0)
xVelocity = 2;
if (x > 320)
xVelocity = -2;
if (y < 0)
yVelocity = 2;
if (y > 240)
yVelocity = -2;
}
void draw(Graphics g) {
g.setColor(Color.RED);
g.fillOval(x, y, 10, 10);
}
}
但它不显示我试图与frame.add的的backgroundColor(一),但仍无法正常工作
它适合我。但是我删除了'a.addCircle();'行,因为我没有完整的'Animation'类。可能有一种方法适合面板和隐藏背景 – BackSlash
Thread.sleep不会帮助。你已经覆盖了你的Aniamtion面板中的一种绘画方法吗?不是 – MadProgrammer
被删除了a.addCircle(),反正它没有工作 – HkGDota