gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:42:11 25 4
gpt4 key购买 nike

我打算编写一个简单的太空射击游戏。我看过 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com