当我选择运行文件来测试代码时,GUI应用程序的菜单栏不会始终显示。我使用的是NetBeans IDE版本7.0.1。我通过选择代码中的任何位置,右键单击鼠标并从结果菜单中选择Run File来测试代码。生成的GUI应用程序有菜单栏,但当我重新运行应用程序时,菜单栏不在那里,但当重新运行它时,会出现菜单栏。也许你可以测试一下,看看你在运行程序时是否遇到了同样的问题?在运行程序之前,是否有某种残余内存需要清除?这是代码:
public static void main(String[] args) {
JFrame main = new JFrame("Main");
main.setVisible(true);
main.setSize(600, 600);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints contraints = new GridBagConstraints();
main.getContentPane().add(panel, BorderLayout.NORTH);
contraints.gridx = 0;
contraints.gridy = 0;
contraints.insets = new Insets(0,0,0,0);
//Adding labels and buttons
JLabel enterUserName = new JLabel("Enter User Name:");
contraints.gridx = 0;
contraints.gridy = 1;
contraints.insets = new Insets(1, 1, 1, 1);
panel.add(enterUserName, contraints);
JLabel enterPassWord = new JLabel("Enter Password:");
contraints.gridx = 0;
contraints.gridy = 2;
contraints.insets = new Insets(1, 1, 1, 1);
panel.add(enterPassWord, contraints);
JButton logInButton = new JButton("Login");
contraints.gridx = 0;
contraints.gridy = 3;
contraints.insets = new Insets(1, 1, 1, 1);
panel.add(logInButton, contraints);
logInButton.addActionListener(new helpAbout());
//Adding menu bar and menubar items
JMenuBar menuBar = new JMenuBar();
main.setJMenuBar(menuBar);
contraints.gridx = 0;
contraints.gridy = 0;
contraints.insets = new Insets(0, 0, 0, 0);
JMenu file = new JMenu("File");
menuBar.add(file, contraints);
JMenu help = new JMenu("Help");
menuBar.add(help, contraints);
//Adding menu bar functionality
JMenuItem exit = new JMenuItem("Exit");
file.add(exit);
exit.addActionListener(new fileExit());
JMenuItem about = new JMenuItem("About");
help.add(about);
about.addActionListener(new helpAbout());
}
static class helpAbout implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JFrame test = new JFrame("About");
test.setVisible(true);
test.setSize(200, 200);
JLabel label2 = new JLabel("About");
JPanel panel2 = new JPanel();
test.add(panel2);
panel2.add(label2);
}
}
static class fileExit implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
在构建框架后调用setVisible(true)
。
如果将布局/控件添加到可见窗体(在其他情况下可能需要这样做),则需要在框架/面板上调用revalidate()
。
代码行main.setVisible(true);
必须是进入main method
的最后一个代码行