java - 使用 GridBagLayout 添加 JTextField 时,Swing 组件不会显示
问题描述
我正在使用 GridBagLayout 处理带有 JLabel 组件的 JPanel。当我在没有 JTextFields 的情况下运行我的程序时,它运行得很好。但是,当我尝试添加 JTextField 时,所有组件都会丢失。这是我的代码:
super("Scheduling Algorithm Simulator");
setSize(new Dimension(500, 550));
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
JPanel pane = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
processLabel = new JLabel("Process", SwingConstants.CENTER);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0.5;
c.gridx = 0;
c.gridy = 0;
pane.add(processLabel, c);
btLabel = new JLabel("Burst Time", SwingConstants.CENTER);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0.5;
c.gridx = 1;
c.gridy = 0;
pane.add(btLabel, c);
p1 = new JLabel("P1", SwingConstants.CENTER);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0.5;
c.gridx = 0;
c.gridy = 1;
pane.add(p1, c);
p2 = new JLabel("P2", SwingConstants.CENTER);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0.5;
c.gridx = 0;
c.gridy = 2;
pane.add(p2, c);
p3 = new JLabel("P3", SwingConstants.CENTER);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0.5;
c.gridx = 0;
c.gridy = 3;
pane.add(p3, c);
p4 = new JLabel("P4", SwingConstants.CENTER);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0.5;
c.gridx = 0;
c.gridy = 4;
pane.add(p4, c);
当我添加这行代码时:
bt1 = new JTextField();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0.5;
c.gridx = 1;
c.gridy = 1;
pane.add(bt1, c);
当我运行程序时,所有组件都会突然丢失。我的代码有什么问题?(JPanel 对象已在我的代码中添加到 JFrame)
解决方案
需要调用 pack() 来显示所有内容。
推荐阅读
- python - `没有为所需参数提供值:图形 ql 数据库中的 id` 错误
- jquery - 猫头鹰轮播不工作,图像在顶部堆叠一个
- python - SSL WRONG_VERSION_NUMBER _ssl.c:1124
- charts - 在折线图中,当我删除 y 轴时,线条超出了高度
- postgresql - 在自引用表上触发
- node.js - 如何使用 JSON 实现此功能?
- python - 设置 vscode 以便 python 导入找到模块
- c# - Kendo MVC 下拉菜单 - 删除选项标签时的空白
- ruby - 从 Ruby 数据哈希中提取值并将值连接到单个连续字符串中
- laravel-5 - Laravel PHPunit 重定向到本地主机