1
我試圖創建一個動畫,其中給定數量的圖標從框架的左側開始並移動到屏幕的右側。圖標垂直排列,每個圖標應該在自己的線程上運行。如何正確執行多線程以便各個線程上的圖標一起移動到屏幕上?
如何獲取所有圖標來做到這一點?當我創建每個賽車手時,我嘗試調整posY
,但到目前爲止,我只能獲得創建的最後一名賽車手來顯示。
import javax.swing.*;
import java.awt.*;
public class Races {
private JFrame frame;
private JPanel gui;
private Icon img;
private int imgWidth;
private int imgHeight;
private int numOfRacers; // num of threads/racers
public static void main(String[] args) {
new Races(5);
}
public Races(int num) {
numOfRacers = num;
createGUI();
frame.add(gui);
frame.pack();
frame.setVisible(true);
}
private void createGUI() {
frame = new JFrame("Off to the Races - by Brienna Herold");
gui = new JPanel();
gui.setPreferredSize(new Dimension(imgWidth * 20, imgHeight * numOfRacers));
img = new ImageIcon("races.png");
imgWidth = img.getIconWidth();
imgHeight = img.getIconHeight();
int posY = 0;
for (int i = 0; i < numOfRacers; i++) {
System.out.println("Starting new thread..." + posY);
racer = new Racer(posY);
Thread racerThread = new Thread(racer);
racerThread.start();
posY += imgHeight;
}
}
protected class Racer extends JPanel implements Runnable {
private int lastPosX;
private int posX;
private int posY;
public Racer(int _posY) {
posX = 0;
posY = _posY;
}
@Override
public void paintComponent(Graphics g) {
// Call the method on the JPanel
super.paintComponent(g);
img.paintIcon(gui, g, posX, posY);
//posY += imgHeight;
posX += lastPosX + 3;
}
@Override
public void run() {
while (true) {
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
}
哦。讓我試試這個。 – briennakh
不是你不只是繪畫。除非將組件添加到框架,否則無法繪製組件。 – camickr
我現在明白了。我要去研究它。 – briennakh