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

时间:2011-12-11 12:34:55

标签: java swing graphics graphics2d

这是我的代码:

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);
    }

}

屏幕频繁闪烁。我尝试在run方法中更改sleep()调用中的值,但它无法解决问题。

如何阻止屏幕闪烁?

2 个答案:

答案 0 :(得分:4)

  

屏幕频繁闪烁。

在EDT上睡觉的经典迹象。这不是自定义绘画的方式。使用Swing Timer调用repaint()

How to Use Swing Timers&在教程中也是Performing Custom Painting

答案 1 :(得分:2)

添加JPanel的孩子进行绘图。这默认为setDoubleBuffered(true),因此没有闪烁。在那里画画。

安德鲁·汤普森关于计时器的暗示更为重要。