Java Swing, paint(), paintComponent(), repaint()

在java的小游戏编程中,如果主人公移动,或者组件之间发生碰撞,等,需要重绘界面。

如果是用awt的canvas, 常用的策略是:增加一个BufferedStrategy对象, 然后再调用canvas对象的createBufferedStrategy()等。

在Swing中,比较好用的方法是:paintComponent()加上repaint(),不用paint()的原因是:

Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren().


用法如下:

public class MyPanel extends JPanel{
    public void paintComponent(Graphics g){
    super.paintComponent(g);//消去之前的画面,如果用paint(), 不用写这行代码,
    g.draw([whatever you want]);//画上新的画面 
    ...
    ...
    }
}


public class MyFrame extends JFrame{
    public MyFrame(){
    MyPanel myPanel = new MyPanel();
    myPanel.repaint();

    }
}   

参考:

https://stackoverflow.com/questions/16875572/paint-repaint-paintcomponent

https://stackoverflow.com/questions/10768619/paint-and-repaint-in-java

原文地址:https://www.cnblogs.com/yizhaoAI/p/10005296.html