2012-06-08 41 views
1

我想製作2D遊戲。我開始製作繪畫課,但是我遇到了一個問題:ActionListener不起作用。它不會畫出或輸出我的信息來說它正在工作。這裏是代碼:ActionListener似乎不工作?

public class Drawing extends JPanel implements ActionListener { 

    private int count = 0; 

    public void actionPerformed(ActionEvent e) { 
     count++; 
     repaint(); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     System.out.println("Hi"); 
     g.setColor(Color.black); 
     g.clearRect(0, 0, Boot.WIDTH, Boot.HEIGHT); 
     g.fillRect(0, 0, Boot.WIDTH, Boot.HEIGHT); 

     g.setColor(Color.white); 
     g.drawString("Path count: " + count, 50, 50); 
    } 
} 

我會認爲這將工作,因爲我在其他項目中使用這種繪圖方式。這會導致什麼?

回答

4

您不應該保留對Graphics對象的引用並直接調用paint()。您應該調用repaint(),然後等待Swing調用paintComponent()方法,您應該重寫以在Swing作爲參數傳遞給該方法的Graphics對象上執行自定義繪畫。

查看http://java.sun.com/products/jfc/tsc/articles/painting/index.html瞭解更多信息。

public class Drawing extends JPanel implements ActionListener { 

    private int count = 0; 

    public void actionPerformed(ActionEvent e) { 
     count++; 
     repaint(); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     System.out.println("Hi"); 
     g.setColor(Color.black); 
     g.clearRect(0, 0, Boot.WIDTH, Boot.HEIGHT); 
     g.fillRect(0, 0, Boot.WIDTH, Boot.HEIGHT); 

     g.setColor(Color.white); 
     g.drawString("Path count: " + count, 50, 50); 
    } 
} 
+0

@Duncan Palmer和Boot.frame.getGraphics(),什麼都不做,會走在第一個Swing事件在內部重新繪製的JComponent,什麼也不做,不保存設置爲BufferedImage +1 – mKorbel

+0

好,使用代碼只油漆和輸出一次。 –

+0

@Duncan:該代碼適合我。 1+ –