問題描述
多線程圖形 (multithreading Graphics)
我正在嘗試實現一個程序,在該程序中我繪製多個圓圈並讓它們隨機穿過框架。我想為每個圈子創建一個線程,但由於某種原因它不起作用。當我實例化幾個圓圈時,框架中只出現一個。這是我的代碼
import java.awt.*;
import javax.swing.*;
public class Ball extends JPanel implements Runnable {
private Color color;
private int xPosition;
private int yPosition;
private int xDir;
private int yDir;
private int radius;
private int xSpeed;
private int ySpeed;
private static JFrame frame;
public Ball(int xPos, int yPos)
{
color = new Color((int) (Math.random()*254), (int) (Math.random()*254), (int) (Math.random()*254));
System.out.println(color);
radius = 10;
xPosition = xPos;
yPosition = yPos;
xDir = ‑1;
yDir = ‑1;
xSpeed = 10;
ySpeed = 10;
}
public void paint(Graphics e){
super.paint(e);
Graphics2D g = (Graphics2D) e;
g.setColor(color);
g.fillOval(xPosition, yPosition, radius, radius);
//setSpeed();
}
public void setSpeed()
{
xSpeed = (int) (Math.random() * 10);
}
public void moveBall()
{
if(xPosition >= 390)
{
xDir *= ‑1;
}
else if(xPosition <= 0)
{
xDir *= ‑1;
}
if(yPosition >= 390)
{
yDir *= ‑1;
}
else if(yPosition <= 0)
{
yDir *= ‑1;
}
xPosition = xPosition + ( xDir * xSpeed);
yPosition = yPosition + (yDir * ySpeed);
}
public static void main(String[] args) {
// TODO Auto‑generated method stub
frame = new JFrame("Ball Bouncer");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Ball b1 = new Ball(25, 25);
Ball b2 = new Ball(50, 50);
b1.setSpeed();
//b2.setSpeed();
Thread a1 = new Thread(b1);
Thread a2 = new Thread(b2);
frame.setVisible(true);
System.out.println(a2.getState());
a1.start();
a2.start();
System.out.println(a1.getId());
System.out.println(a2.getId());
}
@Override
public void run() {
while(true)
{
frame.getContentPane().add(this);
moveBall();
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
參考解法
方法 1:
Ball (Your class) extends JPanel.
If you add more than one JPanel to a JFrame, only last one you added will be visible.
(by Ihsan Hashem、Mayuso)