问题
I am working on a snake game project. I have three java files named:
Engine.javaGameBoard.javaSnake.java
I have added two JFrames in this project. In the first frame are three buttons:
playrulesexit
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