2014-11-27 6 views
1

화면상의 복수 위치를 렌더링하려고합니다. fighters 관련 코드는 다음과 같습니다.스윙 - paintComponent 메서드 내에서 작동하지 않는 목록의 문제

public void run() { 
     double ns = 1000000000.0/tps; 
     double delta = 0; 

     int frames = 0; 
     int updates = 0; 

     long lastTime = System.nanoTime(); 
     long timer = System.currentTimeMillis(); 

     while (running) { 
      long now = System.nanoTime(); 

      delta += (now - lastTime)/ns; 
      lastTime = now; 

      while(delta >= 1) { 
       update(); 
       updates++; 
       delta--; 
      } 

      frame.getContentPane().repaint(); 
      frames++; 

      if(System.currentTimeMillis() - timer >= 1000) { 
       timer += 1000; 
       frame.setTitle(title + " | " + updates + " ups, " + frames + " fps"); 
       frames = 0; 
       updates = 0; 
      } 
     } 

     stop(); 
    } 

    private void update() { 

     if (Math.random() < .1) { 

      Fighter newFighter = new Fighter(); 
      fighterList.add(newFighter); 

     } 

    } 
    public void paintComponent(Graphics g) { 
      super.paintComponent(g); // paint background 
      setBackground(Color.BLUE); 
      System.out.println(fighterList.size()); 
      for (int i = 0; i<fighters; i++) { 
       System.out.println("Attempted"); 
       g.setColor(Color.GREEN); 
       g.drawRect((int) fighterList.get(i).xPos, 
         (int) fighterList.get(i).yPos, 
         fighterList.get(i).radius, 
         fighterList.get(i).radius); 
       System.out.println("Rendered"); 
      } 

     } 
public static void main(String[] args) { 
     Game game = new Game(); 
     game.frame.setContentPane(new Game()); 
     game.frame.setResizable(false); 
     game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     game.frame.setLocationRelativeTo(null); 
     game.frame.setVisible(true); 

     game.start(); 


    } 

문제는 화면에 아무 것도 표시되지 않습니다. 또한 System.out.println(fighterList.size());을 실행하면 실행 위치에 따라 다른 결과가 나타납니다. paintComponent 내부에서 실행될 때 항상 0을 반환하고 내부를 실행하면 update이 적당량을 반환합니다. 이것이 범위와 관련된 문제입니까, 아니면 내가 놓친 다른 것이 있습니까?

+1

1) * "관련 코드는 다음과 같습니다. * 더 빨리 도움을 받으려면 [MCVE] (http://stackoverflow.com/help/mcve) (최소 완성 검증 가능 예제) 또는 [SSCCE] (http://www.sscce.org/) (단락, 자체 포함, 올바른 예). 2) 들여 쓰기 코드 행과 블록의 논리적이고 일관된 형식을 사용하십시오. 들여 쓰기는 코드의 흐름을 따라 가기 쉽도록 만들어졌습니다. –

답변

2

동기화 문제 일 가능성이 큽니다. 메서드는 항상 run() 메서드가 자체 스레드에서 실행되는 동안 EDT (Event Dispatch Thread)에서 호출됩니다. 여기에 update()이 호출되어 새로운 Fighter이 목록에 추가됩니다.

두 (또는 모든) 스레드가 동일한 일관된 데이터를 볼 수 있도록 적절한 동기화가 필요합니다.

또한 재 모델링 중에 모델 (데이터)이 수정 될 수 있으므로 일관성없는 모델이 페인트되지 않도록 모델을 "복제"해야합니다. 또는 복제하지 않으려는 경우 모델에 대한 액세스를 동기화하여 그리는 동안 수정할 수 없습니다.