首页 > 解决方案 > 使用 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)

标签: javaswinglayout-managergridbaglayout

解决方案


需要调用 pack() 来显示所有内容。


推荐阅读