嗨,我用 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();
}
}
非常感谢任何帮助(想法,教程......)