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

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

}

屏幕经常闪烁。我尝试在运行方法中更改 sleep() 调用中的值,但它没有解决问题。

如何阻止屏幕闪烁?

最佳答案

The screen is flickering frequently.

在 EDT 上 sleep 等事情的经典标志。那不是做定制绘画的方法。使用 Swing Timer调用 repaint()

参见 How to Use Swing Timers还有Performing Custom Painting在教程中。

关于java - 绘图时如何防止屏幕闪烁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8463985/

相关文章:

java - 关于Thread的逻辑问题

android - 为什么Android的android.graphics.Color有一个公共(public)构造函数?

C# 画图程序闪烁

java - Try-with-resources 和 ServerSockets

java - 从方法返回数组中不重复的数字

Java 网络 : Currency Converter

java - 仅删除文本区域中的选定文本

java - JTable 不会刷新

c++ - 在 GPU 中使用八叉树组织 3D 体数据

java - 通过索引为 0 的构造函数参数表示的不满足依赖关系