java - 在 Java 中围绕 repaint() 工作

标签 java swing bufferedimage paintcomponent

我打算编写一个简单的太空射击游戏。我看过 repaint() 方法只是一个请求,它不会在每次调用时都执行。我相信我注意到了这一点的影响,因为我的宇宙飞船在移动时往往会稍微滞后。目前我只是在 JPanel 的 paintComponent() 方法中绘制我的飞船,并定期调用 repaint()(我的面板也是 Runnable)。看到 repaint() 可能会把我搞砸,我正试图找到一种方法来解决它,但是我已经没有想法了。我到目前为止的代码:

private void renderGraphics() {
    if (MyImage == null) {
        MyImage = new BufferedImage(getPreferredSize().width,
                getPreferredSize().height, BufferedImage.TYPE_INT_RGB);
    }
    MyGraphics = MyImage.getGraphics();
    MyGraphics.setColor(Color.BLACK);
    MyGraphics.fillRect(0, 0, getPreferredSize().width, getPreferredSize().height);
    MyGraphics.drawImage(ship.getImage(), ship.getCurrentX(), ship.getCurrentY(), null);       
}

我的想法是创建我自己的图形,然后让 JPanel 绘制它,并在我的 run() 方法中继续调用它而不是 repaint(),但是我不知道该怎么做。我很乐意就此事提出任何意见。

最佳答案

有多种方法可以解决这个问题。

最好的方法可能是使用 BufferStrategy 并利用它,我已经包含了一个应该适合您的代码片段。

您可以更进一步,完全放弃 Swing,只需使用 Frame/BufferStrategy。在我的问题中有一个完整的示例(代码片段是从中获取和改编的):

AWT custom rendering - capture smooth resizes and eliminate resize flicker

无论如何,这里有一个BufferStrategy 的实现,您应该可以直接使用它:

// you should be extending JFrame
public void addNotify() {
    super.addNotify();
    createBufferStrategy(2);
}

private synchronized void render() {
    BufferStrategy strategy = getBufferStrategy();
    if (strategy==null) return;
    sizeChanged = false;
    // Render single frame
    do {
        // The following loop ensures that the contents of the drawing buffer
        // are consistent in case the underlying surface was recreated
        do {
            MyGraphics draw = strategy.getDrawGraphics();
            draw.setColor(Color.BLACK);
            draw.fillRect(0, 0, getPreferredSize().width, getPreferredSize().height);
            draw.drawImage(ship.getImage(), ship.getCurrentX(), ship.getCurrentY(), null);
            draw.dispose();

            // Repeat the rendering if the drawing buffer contents 
            // were restored
        } while (strategy.contentsRestored());

        // Display the buffer
        strategy.show();

        // Repeat the rendering if the drawing buffer was lost
    } while (strategy.contentsLost());
}

关于java - 在 Java 中围绕 repaint() 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6896777/

相关文章:

java - 返回一个回文字符串,它不是预期的字符串。背后的机制是什么

java - 当 IN 子句超过 100 或 1000 时,NamedParameterJdbcTemplate 不起作用

Java Hdd 图形表示

java - 在基于 jtextpane 的 jtable 单元格渲染器中裁剪文本行

java - 在不透明的 BufferedImage 上绘制透明的 BufferedImage

java - 属性访问异常 : could not get a field value by reflection getter While using Hibernate

java - JComboBox 宽度

Java BufferedImage.getRGB()——坐标越界

java - 如何使用 Java 中的 AffineTransform 将图像向右翻转?

java - @KafkaListener 不使用消息 - 反序列化问题