当我选择运行文件来测试我的代码时,GUI应用程序的菜单栏不会始终显示。我正在使用NetBeans IDE 7.0.1版。我通过选择代码中的任何位置来测试代码,右键单击鼠标并从结果菜单中选择“运行文件”。生成的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);
}
}
答案 0 :(得分:2)
在构建框架后调用setVisible(true)
。
如果您将布局/控件添加到可见表单(在其他情况下可能要执行此操作),则需要在框架/面板上调用revalidate()
。
答案 1 :(得分:1)
代码行main.setVisible(true);
必须是main method