我尝试创建一个基本的Snake游戏。首先,将开始屏幕显示为JPanel,并且当用户单击“开始”按钮时,该面板将对“ .setVisible(false)”不可见,并且gameScreen(也是JPanel)也将可见。但是在我最小化和最大化窗口之前,在GameScreen类中使用的KeyListener无效。我认为我对第一个clase设置有疑问。
JFrame window = new JFrame("Snake");
window.setUndecorated(true);
window.setLayout(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.setBounds(0, 0, 720, 480);
StartScreen startScreen = new StartScreen(frameWidth, frameHeight);
startScreen.setBounds(0, 0, frameWidth, frameHeight);
startScreen.setVisible(true);
window.add(startScreen);
window.setVisible(true);
while(startScreen.isVisible()){// I know it's bad way but I don't know the better one
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Core.class.getName()).log(Level.SEVERE, null, ex);
}
}
Game gameScreen = new Game(frameWidth, frameHeight, startScreen.getIsClassic());
gameScreen.setBounds(0, 0, frameWidth, frameHeight);
window.add(gameScreen);
gameScreen.setVisible(true);
window.setVisible(true);
是在我的主类中创建JFrame并向其添加JPanels的。
public Game(int weight, int height, boolean isClassic) {
super();
this.setLayout(null);
this.setFocusable(true);
// some other thing about game
this.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println("Yo ho!");
}
@Override
public void keyReleased(KeyEvent e) {
}
});
}
这是我的Game类的构造函数,用于扩展JPanel。
我怎么了?