直接使用frame.add(new GamePanel())就正常,我想加个切换游戏按钮,但又不能操控了
public class text {
public static void main(String[] args) {
JFrame frame = new JFrame("贪吃蛇小游戏");
frame.setBounds(100, 100, 1000, 1000); // 设置窗口的位置和大小
frame.setResizable(false); //窗口大小不可调整,即固定窗口大小
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置关闭事件,游戏可以关闭
Box box2 = Box.createHorizontalBox();
Box box1 = Box.createVerticalBox();
JButton startgame1 = new JButton("单人游戏");
JButton startgame2 = new JButton("双人游戏");
box2.add(startgame1);
box2.add(startgame2);
box1.add(box2);
box1.add(new GamePanel());
frame.add(box1);
frame.setVisible(true); //将窗口展示出来
}
}
初学者,我猜是键盘监听失效了,点击按钮后监听就到按钮上了
如果你是想切换Pane,Jframe里有个方法要调用一下,调用了然后设置才可以切换。
如果你是要加事件,你看看你的事件是加在哪里了,不要给按钮加一个键盘事件