Car
의 데이터 구조를 사용하고이를 paintComonent
방법으로 반복하면됩니다.
List<Car> cars = new ArrayList<>();
....
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Car car : cars) {
car.drawCar(g);
}
}
drawCar
방법처럼 뭔가
public class Car {
int x, y;
public Car(int x, int y) {
this.x = x;
this.y = y;
}
public void drawCar(Graphics g) {
g.setColor(Color.BLACK);
// do everything here as you would in a paintComponent method
}
}
이 더 많은 예제 here 및 here 및 here 및 here 및 here 및 here를 참조하여 Car
클래스에서 온 것입니다.
UPDATE 여기
간단한 예 I는 어떤 애니메이션을 사용 채찍질 일부 "페라리"를 사용하지만, 동일한 기본 점 I 위에있다.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class DrawCar extends JPanel{
private static final int D_W = 400;
private static final int D_H = 400;
List<Car> cars;
public DrawCar() {
cars = new ArrayList<>();
cars.add(new Car(100, 300));
cars.add(new Car(200, 100));
Timer timer = new Timer(50, new ActionListener(){
public void actionPerformed(ActionEvent e) {
for (Car car : cars) {
car.move();
repaint();
}
}
});
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Car car : cars) {
car.drawCar(g);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(D_W, D_H);
}
public class Car {
private static final int INCREMENT = 5;
int x, y;
public Car(int x, int y) {
this.x = x;
this.y = y;
}
public void drawCar(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(x, y, 100, 30);
g.setColor(Color.BLACK); // body
g.fillOval(x + 15, y + 20, 15, 15); // wheel
g.fillOval(x + 60, y + 20, 15, 15); // wheel
g.fillRect(x + 15, y - 20, 60, 20); // top
}
public void move() {
if (x == D_W) {
x = 0;
} else {
x += INCREMENT;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.add(new DrawCar());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
감사합니다. 이것은 대단히 도움이되었습니다. :) – MathMajor
내 ** 업데이트 **에서 일부 애니메이션보기 –
글쎄, 당신은 내가 약 10 분 만에 마지막 2 시간 동안 만들려고했던 프로그램을 만들 수 있었다! 와우! 하하, 그리고 감사 :) – MathMajor