Search code examples
javaswinglayout-managergridbaglayout

Swing components won't show up when adding a JTextField using GridBagLayout


I am working on a JPanel with JLabel components using a GridBagLayout. When I run my program without the JTextFields, it runs just fine. However, when I try to add a JTextField, all the components would gone missing. Here is my code:

    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);

When I add this lines of code:

    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);

All the components would gone missing suddenly when I run the program. What is wrong with my code? (JPanel object was already added to JFrame in my code)


Solution

  • Call to pack() was needed to display everything.