你好,我正在研究關於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