Stan Stan - 10 months ago 58
Java Question

A Starting Menu for a simple game

I am making this small and simple game with Java, and when I start it up, it just starts the game without any menus or something. Now, I want to make it so that if I run the game, there comes a game menu, or starting menu, where you can select new game, and exit. But, how would I do this? I need some help with this.


The game is in a 800x600 screen, and I want like, a menu that takes over the whole 800x600 screen, with just a "Start Game" and a "Exit" button.

Answer Source

The Swing tutorial on menus will be an excellent reference for you as you work through creating a menu.

Here is some sample code for creating a simple menu like you described, assuming your JFrame is called frame.

//Where the GUI is created:
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;

//Create the menu bar.
menuBar = new JMenuBar();

//Build the first menu.
menu = new JMenu("File");
        "File menu");

//JMenuItems show the menu items
menuItem = new JMenuItem("New",
                         new ImageIcon("images/new.gif"));

// add a separator

menuItem = new JMenuItem("Pause", new ImageIcon("images/pause.gif"));

menuItem = new JMenuItem("Exit", new ImageIcon("images/exit.gif"));

// add menu bar to frame

The important classes to know are JMenuBar, JMenu, and JMenuItem.

To handle clicks on those menu items, you need to add an ActionListener for each, using code such as:

menuItem.addActionListener(new ActionListener() { // ...});