gpt4 book ai didi

java - 使用 GridBagLayout 添加 JTextField 时 Swing 组件不会显示

转载 作者:行者123 更新时间:2023-12-02 08:57:07 25 4
gpt4 key购买 nike

我正在使用 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() 来显示所有内容。

关于java - 使用 GridBagLayout 添加 JTextField 时 Swing 组件不会显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60431858/

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