我遇到了在JFrame中切换不同JPanel的问题。我正在尝试向JFrame添加两个不同的面板,用户可以在它们之间来回切换,在程序运行时显示mainPanel
。 mainPanel
正确显示,直到我将buyPanel
添加到框架中。现在我再次显示mainPanel
时出现问题。当我目前运行我的程序时,它显示为空白。问题似乎与最后三行有关,但我无法弄清楚出了什么问题。
我在下面列出了相关代码。
public class TestClass extends JFrame {
private JTextArea welcomeText;
private JComboBox commandsMenu;
private JPanel mainPanel;
private JPanel buyPanel;
private JTextArea buyType;
public TestClass() {
super("TestProgram");
setDefaultLookAndFeelDecorated(true);
setSize(550, 350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Setup elements for main panel (includes commands menu)
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
welcomeText = new JTextArea(10, 10);
welcomeText.setEditable(false);
welcomeText.setLineWrap(true);
welcomeText.setWrapStyleWord(true);
welcomeText.setText(menu());
commandsMenu = new JComboBox();
commandsMenu.setEditable(true);
commandsMenu.setPrototypeDisplayValue("Commands");
commandsMenu.setSize(50, 50);
commandsMenu.addItem("Buy");
commandsMenu.addItem("Quit");
mainPanel.add(commandsMenu);
mainPanel.add(welcomeText);
add(mainPanel);
// Setup elements for buy panel
buyPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
buyType = new JTextArea();
buyType.setText("Type");
buyType.setEditable(false);
buyPanel.add(commandsMenu);
buyPanel.add(buyType);
add(buyPanel);
buyPanel.setVisible(false);
mainPanel.setVisible(true);