我正在使用Java 2D API开发一个使用Java的pacman版本,我试图按照本教程在游戏中包含一个主菜单:https://www.youtube.com/watch?v=FZWX5WoGW00&t=132s。当我尝试像他在视频中那样黑屏时,我收到错误:
Exception in thread "Thread-2" java.lang.IllegalStateException: Component must have a valid peer
我尝试使用 1 而不是 3 的createBufferStrategy(int)
更改缓冲区的数量,这是整个项目中的默认设置,错误消息更改为:
Exception in thread "Thread-2" java.lang.NullPointerException
但这让游戏中的鬼魂开始闪烁
我认为正在产生问题的Game
类中的渲染函数的代码是这样的:
private void render() {
//Use with BufferedImage
BufferStrategy bufferStrategy = this.getBufferStrategy();
if (bufferStrategy == null) {
this.createBufferStrategy(1);
return;
}
Graphics graphics = bufferStrategy.getDrawGraphics();
if(screen == ScreenID.GAME) {
//First iteration: render whole map
if (firstRender) {
mapHandler.renderMap(graphics);
firstRender = false;
}
mapHandler.renderMap(graphics);
entityHandler.render(graphics);
graphics.dispose();
bufferStrategy.show();
} else if(screen == ScreenID.MENU) {
menu.render(graphics);
graphics.dispose();
bufferStrategy.show();
}
}
下面是用于控制帧的Window
类:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Window extends Canvas {
private JFrame frame;
private static final long serialVersionUID = 1L;
public Window(int width, int height, String title, Game game) {
frame = new JFrame(title);
frame.setLocationRelativeTo(null);
frame.getContentPane().setPreferredSize(new Dimension(width, height));
frame.pack();
frame.setMaximumSize(new Dimension(width, height));
frame.setMinimumSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
UserInput controls = new UserInput(game.player,game.screen); //Define os controles do jogo
frame.add(controls);
setFocusable(false);
if(game.screen == ScreenID.GAME) {
frame.add(game);
}else if(game.screen == ScreenID.MENU) {
JPanel myPanel = new JPanel();
JButton buttonGame = new JButton("Jogo");
myPanel.add(buttonGame);
JButton buttonCredits = new JButton("Créditos");
myPanel.add(buttonCredits);
myPanel.setBackground(Color.BLACK);
frame.add(myPanel);
}
frame.setVisible(true);
game.start();
}
}
提前感谢您的任何帮助!
我会尽力帮助你。实际上,我也使用该教程来制作菜单,并且我已使所有工作正常。
- 为什么
Window
会扩展Canvas
,如果你甚至不把它放在Jframe
.这是没有用的; - 如果您使用
game.start()
然后Game.render()
它将在扩展 Canvas 的游戏中绘制。但是,如果game.screen == ScreenID.MENU
返回 true,那么您将只有myPanel
JFrame
,Game.render()
不会绘制。
你能给我你的代码吗,我会尝试做一些事情,除非你已经完成了它。