如何防止绘图时屏幕闪烁?



我的代码:

public class Game extends JComponent implements Runnable {
    World w = null;
    Keyboard keyboard = null;
    Thread game = null;
    /** The constructor. I would like to initialize here */
    public Game(){
        // Create and set up the frame
        JFrame frame = new JFrame("My Game");
        frame.setSize(500, 700);
        frame.setLocationRelativeTo(null);
        frame.add(this);
        frame.setVisible(true);
        world = new World();
        keyboard = new KeyBoard(this);
        game = new Thread(this);
        game.start();
    }
    /** The run() method. I'll be using it as a game loop */
    @Override
    public void run(){
        while(true){
            repaint();
            try {
                Thread.sleep(30);
            } catch (InterruptedException ex) {
                // I don't want to do anything
            }
        }
    }
    /** I was doing a test draw here, but getting an error */
    @Override
    public void paintComponent(Graphics gr){
        Graphics2D g = (Graphics2D) gr;
        g.setColor(Color.BLACK);
        g.fillRect(200, 200, 200, 200);
    }
}

屏幕频繁闪烁。我试着在运行方法中改变sleep()的调用值,但它不能解决问题。

如何阻止屏幕闪烁?

屏幕频繁闪烁

这是在EDT上睡觉的典型表现。这不是定制绘画的方式。使用Swing Timer调用repaint()

参见如何使用摆动计时器&也在教程中执行自定义绘画

添加JPanel的子组件来绘制。这是默认的setDoubleBuffered(true),所以没有闪烁。在那儿画吧。

Andrew Thompson关于计时器的暗示更加重要。

最新更新