我使用AWT和Swing创建了一个非常简单的Java平台游戏(它扩展了Canvas),在您首次加载该游戏时效果很好,但是有时在重新加载游戏时(例如在死亡之后),fps从60-100 +降至大约1。如果您继续加载游戏,它有时会消失,但通常会消失。
当使用NetBeans调试器运行游戏时,FPS丢失的严重性降低并且难以复制。有时(并非总是如此),当游戏重新加载并且FPS下降时,我得到了一个与BufferStrategy相关的“ java.lang.IllegalStateException:组件必须具有有效的对等体”(我在底部粘贴了完整的异常)。
据我所知(并且我与专家相距甚远),它似乎与任何内存泄漏,线程或额外的游戏对象(以前运行时遗留下来的)都不相关,所以我怀疑与BufferStrategy有关。有谁知道如何解决这一问题?预先感谢!
/** The render function */
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
Graphics2D g2d = (Graphics2D) g;
--- code for stuff to draw removed ---
g.dispose();
bs.show();
}
/** Function for reloading the level when pressing the enter key */
if(key == KeyEvent.VK_ENTER) {
JFrame frame = (JFrame) SwingUtilities.getRoot(game);
game.setRunning(false); // This stops the game's thread.
try {
// Added delay to avoid IllegalStateException: Buffers have not been created.
TimeUnit.MILLISECONDS.sleep(400);
frame.dispose();
} catch (InterruptedException ex) {
Logger.getLogger(KeyInput.class.getName()).log(Level.SEVERE, null, ex);
}
//Starts a new JFrame window with the game in it as a component.
Window w = new Window(1200, 900, "Super Sisters", new Game(Game.getSister()));
}
Exception in thread "Thread-$$" java.lang.IllegalStateException: Component must have a valid peer
at java.awt.Component$FlipBufferStrategy.getBackBuffer(Component.java:4067)
at java.awt.Component$FlipBufferStrategy.updateInternalBuffers(Component.java:4050)
at java.awt.Component$FlipBufferStrategy.revalidate(Component.java:4165)
at java.awt.Component$FlipBufferStrategy.revalidate(Component.java:4147)
at java.awt.Component$FlipBufferStrategy.getDrawGraphics(Component.java:4139)