0

嗨,我用 Java 制作了一个扩展小程序的游戏。游戏运行良好,但这项任务的要求之一是应该有一个菜单。例如:当程序运行时,应该出现一个带有“播放”和“退出”选项的屏幕,如果用户点击“播放”,这应该会导致游戏等...

问)有没有办法专门为小程序做到这一点?

我尝试使用以下代码制作菜单,但它不起作用(我认为这仅适用于扩展 JPanel 或 JFrame 不扩展 Applet):

主菜单.java

public class MainMenu extends JFrame {

    int screenWidth = 200;
    int screenHeight = 150;

    int buttonWidth = 100;
    int buttonHeight = 40;

    JButton Play;
    JButton Quit;

    public MainMenu() {
        addButtons();
        addActions();

        Play.setBounds((screenWidth - buttonWidth)/2, 5 , buttonWidth, buttonHeight); // Positions the play button
        Quit.setBounds((screenWidth - buttonWidth)/2, 10 , buttonWidth, buttonHeight);

        //Adding buttons
        getContentPane().add(Play); //add the button to the Frame
        getContentPane().add(Quit);

        pack();
        setVisible(true);
        setLocationRelativeTo(null);
        setSize(screenWidth , screenHeight);
        setTitle("Drop");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

    }

    private void addButtons() {
        Play = new JButton ("Play");
        Quit = new JButton ("Quit");

    }

    private void addActions() {
        Play.addActionListener(new ActionListener() {   // takes play button, adds new actionlistener

            public void actionPerformed(ActionEvent e) { // Turn actionPerformed into variable for usage
                dispose();                               // wipes out Jframe

                Board game = new Board();

                game.run();
            }
        }); //Play Button

        Quit.addActionListener(new ActionListener() {   // takes quit button, adds new actionlistener

            public void actionPerformed(ActionEvent e) { // Turn actionPerformed into variable for usage
                System.exit(0); 
            }
        }); //Quit Button
    }
}

Launcher.java(运行菜单的位置)

public class Launcher {

    public static void main (String[] args){

        new MainMenu();
    }
}

非常感谢任何帮助(想法,教程......)

4

2 回答 2

1

对于一个空间中的许多组件,CardLayout请使用 a ,如此简短示例中所示。

于 2013-05-21T22:50:18.147 回答
0

我刚刚制作了一个基于文本的菜单。

最初将一个变量设置为 true,例如:menu = true 并让 paint 方法在菜单上绘制任何你想要的东西,比如 start...

    if(menu) {

      paint what's on the menu

    }

然后当用户单击菜单中的某个选项时,将菜单变量设置为 false,即 menu = false。

您需要获取鼠标输入来获取用户的输入,因此请使用鼠标侦听器附带的鼠标按下或鼠标单击方法。

将其设置为 false 后,获取 paint 方法来绘制游戏。IE

  if(!menu) {

  paint the game

  }

几乎是一堆 if 语句。

希望这可以帮助某人。

于 2013-06-03T02:32:45.290 回答