开发者

A Starting Menu for a simple game

开发者 https://www.devze.com 2023-02-25 12:25 出处:网络
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 m

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, wh开发者_开发知识库ere you can select new game, and exit. But, how would I do this? I need some help with this.

Edit:

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.


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");
menu.setMnemonic(KeyEvent.VK_F);
menu.getAccessibleContext().setAccessibleDescription(
        "File menu");
menuBar.add(menu);

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

// add a separator
menu.addSeparator();

menuItem = new JMenuItem("Pause", new ImageIcon("images/pause.gif"));
menuItem.setMnemonic(KeyEvent.VK_P);
menu.add(menuItem);

menuItem = new JMenuItem("Exit", new ImageIcon("images/exit.gif"));
menuItem.setMnemonic(KeyEvent.VK_E);
menu.add(menuItem);

// add menu bar to frame
frame.setJMenuBar(theJMenuBar);

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() { // ...});


You could subclass JFrame, add two JButtons to it and show that frame when needed.


Set a JMenuBar to the JFrame (or JApplet). Add JMenu(s) to the JMenuBar. Add JMenuItem(s) to the JMenu(s). Add ActionListener(s) to the JMenuItem(s).

Google 'java+tutorial+classname' for more details of each.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号