gpt4 book ai didi

java - 当我使用运行文件进行测试时,NetBeans GUI 设计表现不一致

转载 作者:行者123 更新时间:2023-12-02 00:30:10 25 4
gpt4 key购买 nike

当我选择运行文件来测试我的代码时,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);
}
}

最佳答案

构建框架后调用setVisible(true)

如果您将布局/控件添加到可见表单(您可能希望在其他情况下执行此操作),则需要在框架/面板上调用 revalidate()

关于java - 当我使用运行文件进行测试时,NetBeans GUI 设计表现不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9241878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com