2013-12-11 211 views
0

如何在遊戲方法中調用paint方法?如何在java中使用其他方法調用Graphics2D方法?

如果我用命令調用「new paint();」這是行不通的

// Main 
public Game() { 
    super(); 
    setTitle("Breakout"); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    setSize(500, 500); 
    setLocationRelativeTo(null); 
    setIgnoreRepaint(true); 
    setResizable(false); 
    setVisible(true); 
} 

// Grafica 
class paint extends JPanel { 

    public paint(Graphics2D g) { 
     super.paint(g); 
     g.setColor(Color.black); 

    } 

} 
+0

你不能那樣做。相反,每次繪製時都需要重繪整個遊戲。 – SLaks

回答

0

大多數程序員使用受保護的擺動方法的paintComponent(圖形克)在JPanel中的超類匿名調用重繪()來改變遊戲的價值觀和更改組件的外觀。使用SwingTimer會在預定的時間內更新結果。

public class game extends JPanel implements ActionListener{ 

     int camX, camY; 
     int update_time = 5;// in milliseconds... 
     Graphics2D g2d; 
     Image image; 
     Timer t; 

    public game(){ 

      t = new Timer(update_time, this);// given "this" is an ActionListener... 
      t.start();// calls actionPerformed method every 5ms... 

    } 


    public void actionPerformed(ActionEvent e){ 

      repaint();//calls paintComponent() method... 

    } 


     public void paintComponent(Graphics g){ 

      super.paintComponent(g); 
      g2d = (Graphics2D)g; 

      g2d.drawImage(image, camX, camY, this); 
      //Do graphical stuff 
     } 



} 
相關問題