2013-03-24 24 views
2

我遇到了一個奇怪的問題,我無法解決。我有兩班JFrame類:JFrame沒有從獨立的類更新圖形

public class TowerDefenceFrame extends JFrame { 

public TowerDefenceFrame() { 
    super("Tower Defence"); 
    setSize(1023, 708); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    //setResizable(false); 
} 

public static void main(String[] args) { 

    TowerDefenceFrame tdf = new TowerDefenceFrame(); 
    tdf.setVisible(true); 
    Map.main(args); 
    } 
} 

和圖形類:

public class Board extends JPanel implements ActionListener { 
BufferedImage road; 
BufferedImage grass; 
Timer time; 

public Board() { 
    setFocusable(true); 
    time = new Timer(5, this); 
    time.start(); 

    try { 
     road = ImageIO.read(new File("../road.png")); 
     grass = ImageIO.read(new File("../grass.png")); 
    } catch (IOException ex) { 
     Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex); 
    } 


} 

public void actionPerformed(ActionEvent e) { 
    repaint(); 

} 

public void paint(Graphics g) { 
    super.paint(g); 

     for (int i = 0; i <= Map.mapWidth - 1; i++) { 
      for (int l = 0; l <= Map.mapHeight - 1; l++) { 

      if (Map.mapArray[l][i] == 1) { 
       g.drawImage(road, (Map.blockSize * i), (Map.blockSize * l), this); 

      } else if (Map.mapArray[l][i] == 0) { 
       g.drawImage(grass,(Map.blockSize * i), (Map.blockSize * l), this); 
      } 

     } 





    } 
     repaint(); 

    } 
} 

當我運行JFrame中出現的應用程序,但是從局級顯卡沒有。我正在尋找這個問題的答案,並找不到一個。我注意到,當我調整JFrame的大小時,板面上的圖像出現了。這讓我相信我不得不更新板類來獲取圖形。我試着在我的JFrame類中添加一個計時器循環來每隔1/2秒添加Board類。它沒有工作。我一直難住這個問題一段時間,我想知道你是否有任何可以幫助,

謝謝。

+0

重寫的方法是paintComponent(Graphics)。所有的擺動組件只能從事件派發線程使用,而不能從主線程使用。 – 2013-03-24 14:17:47

回答

2

類與諸如JAppletJFrameJ開始是Swing,並且AppletFrameAWT。方法paint()AWT類一起使用,但您使用的是JPanelJFrame

而且,因爲你在paint()方法調用super(你會變成paintComponent),你必須@Override它才能正常工作。

+0

我想繼續使用Swing,我將如何使用Swing相當於油漆?謝謝你的幫助,尼克。 – 2013-03-24 15:13:47

+1

@NickHaughton'paintComponent'是'Swing'。 – syb0rg 2013-03-24 15:14:30

+0

我實現了你所建議的代碼更改,但是我仍然得到相同的錯誤: [這是更新的代碼](http://pastebin.com/9TLP1q11) – 2013-03-24 15:26:22