when i click JButton i want that game should start

心不动则不痛 提交于 2020-01-08 06:25:14

问题


I am working on a snake game project. I have three java files named:

  • Engine.java
  • GameBoard.java
  • Snake.java

I have added two JFrames in this project. In the first frame are three buttons:

  • play
  • rules
  • exit

When we click to rules button it opens rules jframe (it's working). When we click play button it should run the snake game. Please suggest me what should i do when i click play button to actually starts the game.

This is the code i copied in play button actionPerformed method:

        JFrame frame = new JFrame("SnakeGame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        Canvas canvas = new Canvas();
        canvas.setBackground(Color.black);
        canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE * GameBoard.TILE_SIZE, GameBoard.MAP_SIZE * GameBoard.TILE_SIZE));
        frame.add(canvas);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        new Engine(canvas).startGame();

回答1:


Add an ActionListener to your "play" button that calls the appropriate start method.




回答2:


I don't know, if I understand your question correctly: Your Snake.java is a GUI? If so, then make an object of your GUI "Snake", when you click on the play-button:

JButton play = new JButton("play");

play.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e)
        {
            Snake play = new Snake();
        }
});

Hope that helps.



来源:https://stackoverflow.com/questions/18956965/when-i-click-jbutton-i-want-that-game-should-start

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!