万事如意,
我正在为一个项目编写一个主菜单。菜单正确显示。我还为菜单上的三个按钮设置了 ActionListener。
我希望做的是在用户选择“开始新游戏”时将 JPanel 重用于一组新的单选按钮。
但是,编写 ActionPerformed 以从 JPanel 中删除现有组件让我感到困惑。我知道 removeAll 在某种程度上很重要,但不幸的是 NetBeans 告诉我我不能在 ActionPerformed 内的 mainMenu JPanel 对象上调用它。因此,我在下面的代码中将其注释掉了,但将其保留了下来,以便您可以看到我要做什么。
感谢您的想法或提示。
这是我的主要代码:
public class Main {
public static void main(String[] args) {
MainMenu menu = new MainMenu();
menu.pack();
menu.setVisible(true);
}
}
这是我的主菜单代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainMenu extends JFrame implements ActionListener {
JButton startNewGame = new JButton("Start a New Game");
JButton loadOldGame = new JButton("Load an Old Game");
JButton seeInstructions = new JButton("Instructions");
public MainMenu() {
super("RPG Main Menu");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainMenu = new JPanel();
mainMenu.setLayout(new FlowLayout());
startNewGame.setMnemonic('n');
loadOldGame.setMnemonic('l');
seeInstructions.setMnemonic('i');
startNewGame.addActionListener(this);
loadOldGame.addActionListener(this);
seeInstructions.addActionListener(this);
mainMenu.add(startNewGame);
mainMenu.add(loadOldGame);
mainMenu.add(seeInstructions);
setContentPane(mainMenu);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source == startNewGame) {
// StartNewGame code goes here
// mainMenu.removeAll();
}
if (source == loadOldGame) {
// LoadOldGame code goes here
}
if (source == seeInstructions) {
// Quit code goes here
}
}
}