G'day全部,难以从Jpanel中删除所有组件
我正在编写项目的主菜单。菜单正常显示。我还为菜单上的三个按钮设置了ActionListeners。
当用户选择“开始新游戏”时,我希望做的是重新使用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);
}
}
这里是我的MainMenu代码:
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
}
}
}
谢谢扎克。我会考虑CardLayout。 – elwynn 2009-02-22 07:30:11