Search code examples
javagridbaglayout

Placing JLabel in the top left corner of a GridBagLayout


I'm using GridBagLayout and I want to position my JLabel and textfield on the top left corner of my JPanel. I know this question might probably be a duplicate but I couldn't find one that could explain why my code ended up centered.

    JLabel user = new JLabel(ss[0]);
    JLabel av = new JLabel(ss[1]);
    JTextField ufield = new JTextField("");

    user.setBorder(BorderFactory.createLineBorder(Color.black));
    av.setBorder(BorderFactory.createLineBorder(Color.black));
    ufield.setBorder(BorderFactory.createLineBorder(Color.black));

    //User Label
    c.anchor = GridBagConstraints.NORTHWEST;
    c.gridx = 0;
    c.gridy = 0;
    c.weightx = 1;
    c.insets = new Insets(2, 0, 0, 2);
    p.add(user, c);

    //User TextField
    c.fill = GridBagConstraints.BOTH;
    c.gridx = 1;
    c.gridy = 0;
    c.gridwidth = 5;
    c.gridheight = 1;
    c.weightx = 2;
    c.insets = new Insets(5, 1, 1, 5);
    p.add(ufield, c);

    //Available Label
    c.fill = GridBagConstraints.NORTHWEST;
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.weightx = 1;
    c.insets = new Insets(5, 1, 1, 5);
    p.add(av, c);

    f.repaint();
    f.revalidate();

This ends up looking like this : enter image description here

I want it to be near the top instead of at the center


Solution

  • The JLabel and textfield are in fact aligned at the top left of the JPanel, however, the JPanel is not at the top left of the JFrame (which I'm guessing is the variable f), therefore overall it appears centered rather than on the top left.

    You have to control the layout of the JFrame when you add the JPanel to it. You could do it using a BorderLayout like:

    f.getContentPane().setLayout(new BorderLayout());
    f.add(p, BorderLayout.PAGE_START);