我在向我的主 JFrame 添加面板并立即隐藏它时遇到问题,只有在按下按钮时才使其可见。这是我的代码。寻找有关问题所在的任何见解。我尝试添加到面板的标签也没有显示。
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cis2430_a4;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* @author Tristan
*/
public class MainWindow extends JFrame implements ActionListener{
public static final int WIDTH = 600;
public static final int HEIGHT = 700;
private JPanel addPanel;
public MainWindow()
{
super("Day Planner");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JLabel intro1 = new JLabel("Welcome to your Day Planner", JLabel.CENTER);
add(intro1, BorderLayout.NORTH);
JLabel intro2 = new JLabel("Please choose an option from the menu bar above.", JLabel.CENTER);
add(intro2, BorderLayout.CENTER);
JMenu commands = new JMenu("Commands");
JMenuItem addOption = new JMenuItem("Add");
addOption.addActionListener(this);
commands.add(addOption);
JMenuItem searchOption = new JMenuItem("Search");
searchOption.addActionListener(this);
commands.add(searchOption);
JMenuBar menuBar = new JMenuBar();
menuBar.add(commands);
setJMenuBar(menuBar);
JButton button = new JButton("Add");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
//add panel
addPanel = new JPanel();
addPanel.setLayout(new BorderLayout());
addPanel.setSize(600,400);
addPanel.setBackground(Color.CYAN);
addPanel.add(new JLabel("add panel"), BorderLayout.CENTER);
add(addPanel, BorderLayout.CENTER);
addPanel.setVisible(false);
}
@Override
public void actionPerformed(ActionEvent ae)
{
/*String menuChoice = ae.getActionCommand();
if (menuChoice.equals("Add")){
addPanel.setVisible(true);
}*/
add(addPanel);
//addPanel.setVisible(true);
}
}