2016-04-29 83 views
6

我一直在做一個hang子手遊戲來教自己Java。我已經進入了框架的主體。Java hang子手遊戲重畫()不工作

this.add(new PaintSurface(), BorderLayout.CENTER); 

我有:

private class PaintSurface extends JComponent { 
    Shape found = null; 

    public PaintSurface(){ 
     JOptionPane.showMessageDialog(null, "Repainting"); 
     Shape s; 
     msgbox("LL: " + intLivesLost); 
     switch(intLivesLost){ 
     //draw the Hanged man 
     case 10: 
      //Face + KILL 
     case 9: 
      //2nd Arm 
     case 8: 
      //1st Arm 
     case 7: 
      //2nd Leg 
     case 6: 
      //1st Leg 
     case 5: 
      //Body 
     case 4: 
      //Head 
      shapes.add(s); 
     case 3: 
      //Horizontal Bar 
      s = new Line2D.Float(100, 450, 250, 450); 
      shapes.add(s); 
      //Rope 
      s = new Line2D.Float(250, 450, 250, 500); 
      shapes.add(s); 
     case 2: 
      //Vertical Bar 
      s = new Line2D.Float(100, 450, 100, 670); 
      shapes.add(s); 
     case 1: 
      //Stand 
      s = new Line2D.Float(40, 670, 460, 670); 
      shapes.add(s); 
      break; 
     default: 
      break;   
     } 
    } 

    public void paint(Graphics g) { 
     Graphics2D g2 = (Graphics2D)g; 
     g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
       RenderingHints.VALUE_ANTIALIAS_ON); 
     g2.setStroke(new BasicStroke(4)); 
     g2.setColor(Color.BLACK); 

     for (Shape count : shapes){ 
      g2.draw(count); 
     } 
    } 
} 

而且我使用:

repaint(); 

...整個項目中的每個幀被更新時,新的信猜測,不正確猜,新遊戲。

當應用程序第一次運行JOptionPane.showMessageDialog(null,「重繪」);彈出,所以我知道它被稱爲那麼。之後,「重新油漆」彈出不再出現,所以我知道repaint();電話無所事事。我知道代碼正在進行repaint();調用,因爲我在它們之前和之後放置了一個JOptionPane.showMessageDialog。

我已經試過,沒有運氣:

的removeAll();
revalidate();
getContentPane()。repaint();

這個任何提示和技巧,將不勝感激。

編輯:我試過了,因爲你推薦,把代碼放在「paint」中,認爲這是我以前的樣子,而且還沒有工作。不過謝謝。

+0

「public PaintSurface(){...}」是PaintSurface類的構造函數。它只在使用「new PaintSurface()」創建PaintSurface時被調用。你創建形狀對象的邏輯應該放在其他地方(可能是繪製方法,但我不確定,因此這不是答案;)) –

回答

0

我解決了它,把繪圖放在一個單獨的面板上,這一切都工作正常。 感謝您的幫助。

1
  1. 請勿重寫paint,重寫paintComponent或根據需要更新。
  2. 好像你在繪畫,重繪和更新方法之間有混淆。閱讀:https://www.guiguan.net/repaint-paint-and-update/如果您正在進行遊戲,repaint()將導致重新繪製整個組件,因此您將遇到一些性能問題。