2014-11-10 4 views
0

내 프로젝트에는 abstract class Vehicle을 상속하는 클래스 CarTruck이 있습니다. 그런 다음 무작위로 자동차 또는 차량을 총 10 회 추첨해야합니다. 또한 각각의 숫자가 JLabel에 표시 될 것이지만 내 카운트는 JFrame에 0으로 계속 표시됩니다. 여기 내 코드가있다.JLabel을 사용하여 카운트 표시?

package vehiclePackage; 

import java.awt.Graphics; 
import java.util.Random; 

public abstract class Vehicle 
{ 
    public Vehicle() { 
    } 

    public Vehicle(int xLeft, int yTop) { 
    } 

    public abstract void draw(Graphics g2); 
} 

Car 등급 :

package vehiclePackage; 

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Rectangle; 
import java.awt.geom.Ellipse2D; 
import java.awt.geom.Line2D; 
import java.awt.geom.Point2D; 
import java.util.Random; 

public class Car extends Vehicle 
{ 
    private int xLeft; 
    private int yTop; 
    private int ccount; 

    public Car() { } 

    public Car (int x, int y) 
    { 
     super(x,y); 
     this.xLeft = x; 
     this.yTop = y; 
    } 

    //@override 
    public void draw(Graphics g2) 
    { 

     Random rand = new Random(); 

     float red = rand.nextFloat(); 
     float green = rand.nextFloat(); 
     float blue = rand.nextFloat(); 

     Color randomColor = new Color(red, green, blue); 

     Rectangle body = new Rectangle (xLeft, yTop +10, 60, 10); 
     Ellipse2D.Double frontTire = new Ellipse2D.Double (xLeft+10, yTop+20, 10, 10); 
     Ellipse2D.Double rearTire = new Ellipse2D.Double (xLeft+40, yTop+20, 10, 10); 

     Point2D.Double r1 = new Point2D.Double(xLeft+10, yTop+10); 
     Point2D.Double r2 = new Point2D.Double(xLeft+20, yTop); 
     Point2D.Double r3 = new Point2D.Double(xLeft+40, yTop); 
     Point2D.Double r4 = new Point2D.Double(xLeft+50, yTop+10); 

     Line2D.Double frontWindshield = new Line2D.Double(r1,r2); 
     Line2D.Double roofTop = new Line2D.Double(r2,r3); 
     Line2D.Double rearWindshield = new Line2D.Double(r3,r4); 

     ((Graphics2D) g2).setColor(randomColor); 

     ((Graphics2D) g2).fill(body); 
     ((Graphics2D) g2).fill(frontTire); 
     ((Graphics2D) g2).fill(rearTire); 

     ((Graphics2D) g2).draw(body); 
     ((Graphics2D) g2).draw(frontTire); 
     ((Graphics2D) g2).draw(rearTire); 
     ((Graphics2D) g2).draw(frontWindshield); 
     ((Graphics2D) g2).draw(rearWindshield); 
     ((Graphics2D) g2).draw(roofTop); 

    } 
} 

Truck 등급 :

package vehiclePackage; 

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Rectangle; 
import java.awt.geom.Ellipse2D; 
import java.util.Random; 

public class Truck extends Vehicle 
{ 
    private int xLeft; 
    private int yTop; 
    private int tcount; 

    public Truck() 
    { 

    } 
    public Truck (int x, int y) 
    { 
     super(x, y); 
     this.xLeft = x; 
     this.yTop = y; 
    } 

    public void draw(Graphics g2) 
    { 
     Random rand = new Random(); 

     float red = rand.nextFloat(); 
     float green = rand.nextFloat(); 
     float blue = rand.nextFloat(); 

     Color randomColor = new Color(red, green, blue); 

     Rectangle body = new Rectangle (xLeft + 22, yTop +10, 60, 20); 
     Rectangle topCab = new Rectangle(xLeft, yTop + 10, 20, 10); 
     Rectangle bottomCab = new Rectangle(xLeft, yTop + 20, 20, 10); 
     Ellipse2D.Double frontTire = new Ellipse2D.Double (xLeft+6, yTop+30, 10, 10); 
     Ellipse2D.Double midTire = new Ellipse2D.Double (xLeft+25, yTop+30, 10, 10); 
     Ellipse2D.Double mid2Tire = new Ellipse2D.Double (xLeft+35, yTop+30, 10, 10); 
     Ellipse2D.Double backTire = new Ellipse2D.Double (xLeft+55, yTop+30, 10, 10); 
     Ellipse2D.Double back2Tire = new Ellipse2D.Double (xLeft+65, yTop+30, 10, 10); 

     ((Graphics2D) g2).setColor(randomColor); 

     ((Graphics2D) g2).fill(body); 
     ((Graphics2D) g2).fill(bottomCab); 
     ((Graphics2D) g2).fill(frontTire); 
     ((Graphics2D) g2).fill(midTire); 
     ((Graphics2D) g2).fill(mid2Tire); 
     ((Graphics2D) g2).fill(backTire); 
     ((Graphics2D) g2).fill(back2Tire); 

     ((Graphics2D) g2).draw(body); 
     ((Graphics2D) g2).draw(topCab); 
     ((Graphics2D) g2).draw(bottomCab); 
     ((Graphics2D) g2).draw(frontTire); 
     ((Graphics2D) g2).draw(midTire); 
     ((Graphics2D) g2).draw(mid2Tire); 
     ((Graphics2D) g2).draw(backTire); 
     ((Graphics2D) g2).draw(back2Tire); 
    } 
} 

VehicleComponent 등급 :

package vehiclePackage; 

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.util.Random; 

import javax.swing.JComponent; 

public class VehicleComponent extends JComponent 
{ 
    private int x; 
    private int y; 

    private static int ccount = 0; 
    private static int tcount = 0; 


    public void paintComponent(Graphics g) 
    { 
     Graphics2D g2 = (Graphics2D) g; 


     Random rand = new Random(); 

     for (int i = 1; i<=10; i ++) 
     { 

      int vehic = rand.nextInt(2); 
      if (vehic == 0) 
      { 
       x = rand.nextInt(420); 
       y = rand.nextInt(545); 

       Vehicle car = new Car(x, y); 
       car.draw(g2); 
       ccount += 1; 
      } 
      if (vehic ==1) 
      { 
       x = rand.nextInt(420); 
       y = rand.nextInt(545); 
       Vehicle truck = new Truck(x, y); 
       truck.draw(g2); 
       tcount += 1; 

      } 
     } 
    } 
    public String toString() 
    { 
     return "Trucks: " + tcount + ", Cars: " + ccount; 
    } 
} 

VehicleTester :

package vehiclePackage; 

import java.awt.BorderLayout; 
import java.util.Random; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 

public class VehicleViewer { 

    public static void main(String[] args) 
    { 
     // TODO Auto-generated method stub 
     JFrame f = new JFrame(); 

     f.setSize(500,600); 
     f.setTitle("Cars and Trucks"); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     VehicleComponent component = new VehicleComponent(); 
     f.add(component); 
     JLabel runningCount = new JLabel(component.toString()); 
     f.add(runningCount, BorderLayout.SOUTH); 

     f.setVisible(true); 
    } 
} 
+0

'VehicleCompon ent'의'ccount'와'tcount'는'static'이 아니어야합니다. 이것은 VehicleComponent의 모든 인스턴스가 같은 값을 가질 것이라는 것을 의미합니다 ... – MadProgrammer

+0

단순히 숫자를 제한하려고하는 것처럼 보입니다. 화면에 요소가 있습니까? 왜리스트에 추가하지 않겠습니까? – MadProgrammer

+0

좋아, 정적이 없으면 시도했지만 여전히 같은 결과를 얻고 있습니다. – son2323

답변

1

귀하의 문제는 paintComponent 루틴이 호출되기 전에 당신이 레이블 텍스트에 대한 값을 계산하는 것입니다. 일단 호출되면 텍스트는 이전 값으로 남습니다.

내가 제안하는 편집은 어떤 차량을 그려야하는지 계산자를 VehicleComponent으로 이동 한 다음 그릴 시간이되면 미리 채워진 배열을보고 무엇을 그려야할지 결정할 수 있습니다. 카운트는 이미 업데이트됩니다. (당신의 페인트 좌표가 조금 떨어져 있습니다 만 ...)

VehicleComponent

public class VehicleComponent extends JComponent 
{ 
    private int x; 
    private int y; 

    private int ccount = 0; // these shouldn't be static 
    private int tcount = 0; 

    private boolean[] truckOrCar; // simple boolean array (you can change the type as you add more vehicles...) 

    public VehicleComponent() { 
     // figure out your car/truck count here 
     Random rand = new Random(); 
     truckOrCar = new boolean[10]; 

     for (int i = 0; i<10; i ++) 
     { 
      int vehic = rand.nextInt(2); 
      if (vehic == 0) 
      { 
       // false for car 
       truckOrCar[i] = false; 
       ccount += 1; 
      } 
      else { 
       // true for truck 
       truckOrCar[i] = true; 
       tcount += 1; 
      } 
     } 
    } 

    public void paintComponent(Graphics g) 
    { 
     Graphics2D g2 = (Graphics2D) g; 

     Random rand = new Random(); 

     // here just look in your list for what to draw 
     for (int i = 0; i<10; i ++) 
     { 

      // false for car 
      if (!truckOrCar[i]) 
      { 
       x = rand.nextInt(420); 
       y = rand.nextInt(545); 

       Vehicle car = new Car(x, y); 
       car.draw(g2); 
       ccount += 1; 
      } 
      // true for truck 
      else 
      { 
       x = rand.nextInt(420); 
       y = rand.nextInt(545); 
       Vehicle truck = new Truck(x, y); 
       truck.draw(g2); 
       tcount += 1; 
      } 
     } 
    } 

    public String toString() 
    { 
     return "Trucks: " + tcount + ", Cars: " + ccount; 
    } 

} 

페이지의 결과에 대한 업데이트를 참조하십시오

enter image description here

+0

트릭을 마쳤습니다. 감사합니다. – son2323

+0

이것은 컴포넌트가 다시 칠해질 때마다 각 차량의 위치와 색상을 무작위로 추출 할 것입니다 ... 이것이 필요한지 전혀 모르겠지만 절 놀라게 할 것입니다 ...'boolean' 배열을 사용하는 대신 'Vehicle' 배열을 사용하면 각 페인트 사이클마다 같은 위치에 머물러있게됩니다. – MadProgrammer

+0

@MadProgrammer 예, 맞습니다. 프로그래밍 중이라면 그렇게했을 것입니다. 원래의 의도가 밝혀지지 않았기 때문에, 나는 그의 원래 디자인이 왜 작동하지 않고 그것을 고칠 수 있는지 설명하는 간단한 예제를 제공했다. 더 나은 디자인은 연습과 함께 제공됩니다. –

1

난 당신이 이해하지 못하는 것 같아요 무엇 스윙에서 그림이 실제로 어떻게 작동하는지. 회화는 ...

Performing Custom Painting보고 자세한 내용은 Painting in AWT and Swing을 가지고 ... 당신의 컴퍼넌트가 페인트 될 때마다, 완전히 처음부터, 전체 상태를 칠 것으로 예상된다, 즉, 파괴

그래서 당신은 당신의 paintComponent 방법으로 반복 할 것입니다, 만약 당신이 정말로 운이 좋다면, 오직 하나의 차량을 페인트 할 것입니다.

대신 ... 그래서, 우리는 따라서 VehicleComponent을 바꿀 수 ...

List 또는 배열의 어떤 종류의 차량을 유지하고 단순히 paintComponent이 목록을 페인트 할 필요가

public class VehicleComponent extends JComponent { 

    private List<Car> cars; 
    private List<Truck> trucks; 

    private Random rnd = new Random(); 

    public VehicleComponent() { 
     cars = new ArrayList<>(25); 
     trucks = new ArrayList<>(25); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     Graphics2D g2 = (Graphics2D) g; 
     for (Car car : cars) { 
      car.draw(g2); 
     } 
     for (Truck truck : trucks) { 
      truck.draw(g2); 
     } 
    } 

    @Override 
    public String toString() { 
     return "Trucks: " + trucks.size() + ", Cars: " + cars.size(); 
    } 

} 

이제는 구성 요소가 다시 칠해질 때 carstrucks 목록에있는 내용을 페인트합니다 ...

이제 나머지는 내가 r equirements가 올바르게 ...

다음으로, 우리는 새로운 차량을 목록에 추가 할 필요가 있습니다 ...

구성 요소를 업데이트하기위한 방법을 알고, 내가 0-4 사이의 난수를 생성하는 간단한 방법을 쓰고 1에는 Car를 만들고 3에이 Truck, 당신은 당신이 원하는대로로 변경할 수 있습니다 생성합니다. 그것은 내가 addNewVehicle 방법마다 두 번째라는 스윙 Timer를 사용,

public void addNewVehicle() { 

    int value = (int) Math.round(Math.random() * 5); 

    if (value == 1) { 
     if (cars.size() < 10) { 
      cars.add(new Car(getSize())); 
     } 
    } else if (value == 3) { 
     if (trucks.size() < 10) { 
      trucks.add(new Truck(getSize())); 
     } 
    } else { 
     System.out.println("No new toys"); 
    } 
    repaint(); 
} 

업데이트를 트리거하려면 ... 새로운 차량 목록에서 사용할 수있는 공간이 먼저를 작성하기 전에이 있는지 확인합니다 .. .

Timer timer = new Timer(1000, new ActionListener() { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     component.addNewVehicle(); 
     runningCount.setText(component.toString()); 
    } 

}); 
timer.start(); 

addNewVehicle 방법의 무작위 자연에서 추가, 이것은 당신이 차량이 매 초마다 추가 표시되지 않습니다 것을 의미합니다. 이것은 또한 지금

는 도장 공정의 특성상, 내가 대신 색상에게 그들이 때마다 무작위로, 당신의 TruckCar 페인트 방식을 바꾸어 ... 동기화를 유지하는 동시에 runningCount 라벨을 업데이트 그려, 내가 다시 함께 조각 어떤 노력이 될 수 각 인스턴스 지금 대신
public class Car extends Vehicle { 

    private int xLeft; 
    private int yTop; 
    private Color color; 

    public Car(Dimension size) { 
     xLeft = (int) Math.round((Math.random() * size.width - 60)); 
     yTop = (int) Math.round((Math.random() * size.height - 10)); 

     Random rand = new Random(); 

     float red = rand.nextFloat(); 
     float green = rand.nextFloat(); 
     float blue = rand.nextFloat(); 

     color = new Color(red, green, blue); 
    } 

    @Override 
    public void draw(Graphics g2) { 

     Rectangle body = new Rectangle(xLeft, yTop + 10, 60, 10); 
     Ellipse2D.Double frontTire = new Ellipse2D.Double(xLeft + 10, yTop + 20, 10, 10); 
     Ellipse2D.Double rearTire = new Ellipse2D.Double(xLeft + 40, yTop + 20, 10, 10); 

     Point2D.Double r1 = new Point2D.Double(xLeft + 10, yTop + 10); 
     Point2D.Double r2 = new Point2D.Double(xLeft + 20, yTop); 
     Point2D.Double r3 = new Point2D.Double(xLeft + 40, yTop); 
     Point2D.Double r4 = new Point2D.Double(xLeft + 50, yTop + 10); 

     Line2D.Double frontWindshield = new Line2D.Double(r1, r2); 
     Line2D.Double roofTop = new Line2D.Double(r2, r3); 
     Line2D.Double rearWindshield = new Line2D.Double(r3, r4); 

     ((Graphics2D) g2).setColor(color); 

     ((Graphics2D) g2).fill(body); 
     ((Graphics2D) g2).fill(frontTire); 
     ((Graphics2D) g2).fill(rearTire); 

     ((Graphics2D) g2).draw(body); 
     ((Graphics2D) g2).draw(frontTire); 
     ((Graphics2D) g2).draw(rearTire); 
     ((Graphics2D) g2).draw(frontWindshield); 
     ((Graphics2D) g2).draw(rearWindshield); 
     ((Graphics2D) g2).draw(roofTop); 

    } 

} 

public class Truck extends Vehicle { 

    private int xLeft; 
    private int yTop; 
    private Color color; 

    public Truck(Dimension size) { 
     xLeft = (int) Math.round((Math.random() * size.width - 60)); 
     yTop = (int) Math.round((Math.random() * size.height - 20)); 
     Random rand = new Random(); 

     float red = rand.nextFloat(); 
     float green = rand.nextFloat(); 
     float blue = rand.nextFloat(); 

     color = new Color(red, green, blue); 
    } 

    @Override 
    public void draw(Graphics g2) { 

     Rectangle body = new Rectangle(xLeft + 22, yTop + 10, 60, 20); 
     Rectangle topCab = new Rectangle(xLeft, yTop + 10, 20, 10); 
     Rectangle bottomCab = new Rectangle(xLeft, yTop + 20, 20, 10); 
     Ellipse2D.Double frontTire = new Ellipse2D.Double(xLeft + 6, yTop + 30, 10, 10); 
     Ellipse2D.Double midTire = new Ellipse2D.Double(xLeft + 25, yTop + 30, 10, 10); 
     Ellipse2D.Double mid2Tire = new Ellipse2D.Double(xLeft + 35, yTop + 30, 10, 10); 
     Ellipse2D.Double backTire = new Ellipse2D.Double(xLeft + 55, yTop + 30, 10, 10); 
     Ellipse2D.Double back2Tire = new Ellipse2D.Double(xLeft + 65, yTop + 30, 10, 10); 

     ((Graphics2D) g2).setColor(color); 

     ((Graphics2D) g2).fill(body); 
     ((Graphics2D) g2).fill(bottomCab); 
     ((Graphics2D) g2).fill(frontTire); 
     ((Graphics2D) g2).fill(midTire); 
     ((Graphics2D) g2).fill(mid2Tire); 
     ((Graphics2D) g2).fill(backTire); 
     ((Graphics2D) g2).fill(back2Tire); 

     ((Graphics2D) g2).draw(body); 
     ((Graphics2D) g2).draw(topCab); 
     ((Graphics2D) g2).draw(bottomCab); 
     ((Graphics2D) g2).draw(frontTire); 
     ((Graphics2D) g2).draw(midTire); 
     ((Graphics2D) g2).draw(mid2Tire); 
     ((Graphics2D) g2).draw(backTire); 
     ((Graphics2D) g2).draw(back2Tire); 
    } 
} 

를 만들어 색상, 원인을 무작위, 이것은 내가 그것을 테스트하는 데 사용되는 코드는 ...입니다

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Rectangle; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.geom.Ellipse2D; 
import java.awt.geom.Line2D; 
import java.awt.geom.Point2D; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Random; 
import javax.swing.JComponent; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.Timer; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class Test { 

    public static void main(String[] args) { 
     new Test(); 
    } 

    public Test() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
        ex.printStackTrace(); 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

       final VehicleComponent component = new VehicleComponent(); 
       frame.add(component); 
       final JLabel runningCount = new JLabel(component.toString()); 
       frame.add(runningCount, BorderLayout.SOUTH); 

       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 

       Timer timer = new Timer(1000, new ActionListener() { 

        @Override 
        public void actionPerformed(ActionEvent e) { 
         component.addNewVehicle(); 
         runningCount.setText(component.toString()); 
        } 

       }); 
       timer.start(); 
      } 
     }); 
    } 

    public abstract class Vehicle { 

     public abstract void draw(Graphics g2); 
    } 

    public class Car extends Vehicle { 

     private int xLeft; 
     private int yTop; 
     private Color color; 

     public Car(Dimension size) { 
      xLeft = (int) Math.round((Math.random() * size.width - 60)); 
      yTop = (int) Math.round((Math.random() * size.height - 10)); 

      Random rand = new Random(); 

      float red = rand.nextFloat(); 
      float green = rand.nextFloat(); 
      float blue = rand.nextFloat(); 

      color = new Color(red, green, blue); 
     } 

     @Override 
     public void draw(Graphics g2) { 

      Rectangle body = new Rectangle(xLeft, yTop + 10, 60, 10); 
      Ellipse2D.Double frontTire = new Ellipse2D.Double(xLeft + 10, yTop + 20, 10, 10); 
      Ellipse2D.Double rearTire = new Ellipse2D.Double(xLeft + 40, yTop + 20, 10, 10); 

      Point2D.Double r1 = new Point2D.Double(xLeft + 10, yTop + 10); 
      Point2D.Double r2 = new Point2D.Double(xLeft + 20, yTop); 
      Point2D.Double r3 = new Point2D.Double(xLeft + 40, yTop); 
      Point2D.Double r4 = new Point2D.Double(xLeft + 50, yTop + 10); 

      Line2D.Double frontWindshield = new Line2D.Double(r1, r2); 
      Line2D.Double roofTop = new Line2D.Double(r2, r3); 
      Line2D.Double rearWindshield = new Line2D.Double(r3, r4); 

      ((Graphics2D) g2).setColor(color); 

      ((Graphics2D) g2).fill(body); 
      ((Graphics2D) g2).fill(frontTire); 
      ((Graphics2D) g2).fill(rearTire); 

      ((Graphics2D) g2).draw(body); 
      ((Graphics2D) g2).draw(frontTire); 
      ((Graphics2D) g2).draw(rearTire); 
      ((Graphics2D) g2).draw(frontWindshield); 
      ((Graphics2D) g2).draw(rearWindshield); 
      ((Graphics2D) g2).draw(roofTop); 

     } 

    } 

    public class Truck extends Vehicle { 

     private int xLeft; 
     private int yTop; 
     private Color color; 

     public Truck(Dimension size) { 
      xLeft = (int) Math.round((Math.random() * size.width - 60)); 
      yTop = (int) Math.round((Math.random() * size.height - 20)); 
      Random rand = new Random(); 

      float red = rand.nextFloat(); 
      float green = rand.nextFloat(); 
      float blue = rand.nextFloat(); 

      color = new Color(red, green, blue); 
     } 

     @Override 
     public void draw(Graphics g2) { 

      Rectangle body = new Rectangle(xLeft + 22, yTop + 10, 60, 20); 
      Rectangle topCab = new Rectangle(xLeft, yTop + 10, 20, 10); 
      Rectangle bottomCab = new Rectangle(xLeft, yTop + 20, 20, 10); 
      Ellipse2D.Double frontTire = new Ellipse2D.Double(xLeft + 6, yTop + 30, 10, 10); 
      Ellipse2D.Double midTire = new Ellipse2D.Double(xLeft + 25, yTop + 30, 10, 10); 
      Ellipse2D.Double mid2Tire = new Ellipse2D.Double(xLeft + 35, yTop + 30, 10, 10); 
      Ellipse2D.Double backTire = new Ellipse2D.Double(xLeft + 55, yTop + 30, 10, 10); 
      Ellipse2D.Double back2Tire = new Ellipse2D.Double(xLeft + 65, yTop + 30, 10, 10); 

      ((Graphics2D) g2).setColor(color); 

      ((Graphics2D) g2).fill(body); 
      ((Graphics2D) g2).fill(bottomCab); 
      ((Graphics2D) g2).fill(frontTire); 
      ((Graphics2D) g2).fill(midTire); 
      ((Graphics2D) g2).fill(mid2Tire); 
      ((Graphics2D) g2).fill(backTire); 
      ((Graphics2D) g2).fill(back2Tire); 

      ((Graphics2D) g2).draw(body); 
      ((Graphics2D) g2).draw(topCab); 
      ((Graphics2D) g2).draw(bottomCab); 
      ((Graphics2D) g2).draw(frontTire); 
      ((Graphics2D) g2).draw(midTire); 
      ((Graphics2D) g2).draw(mid2Tire); 
      ((Graphics2D) g2).draw(backTire); 
      ((Graphics2D) g2).draw(back2Tire); 
     } 
    } 

    public class VehicleComponent extends JComponent { 

     private int x; 
     private int y; 

     private List<Car> cars; 
     private List<Truck> trucks; 

     private Random rnd = new Random(); 

     public VehicleComponent() { 
      cars = new ArrayList<>(25); 
      trucks = new ArrayList<>(25); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(400, 400); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      Graphics2D g2 = (Graphics2D) g; 
      for (Car car : cars) { 
       car.draw(g2); 
      } 
      for (Truck truck : trucks) { 
       truck.draw(g2); 
      } 
     } 

     public void addNewVehicle() { 

      int value = (int) Math.round(Math.random() * 5); 

      if (value == 1) { 
       if (cars.size() < 10) { 
        cars.add(new Car(getSize())); 
       } 
      } else if (value == 3) { 
       if (trucks.size() < 10) { 
        trucks.add(new Truck(getSize())); 
       } 
      } else { 
       System.out.println("No new toys"); 
      } 
      repaint(); 
     } 

     @Override 
     public String toString() { 
      return "Trucks: " + trucks.size() + ", Cars: " + cars.size(); 
     } 

    } 
} 
관련 문제