Search code examples
javaswingjpanellayout-managergridbaglayout

GridBagLayout constraints not working?


Here is my code that uses GridbagLayout

public IntroPanel(){
    JPanel intro = new JPanel(new GridBagLayout());
    JLabel label1 = new JLabel("Test test test");
    label1.setFont(new Font("Helvetica", Font.PLAIN, 40));
    label1.setHorizontalAlignment(SwingConstants.LEFT);
    JLabel label2 = new JLabel("test2 test2 test2");

    setPreferredSize(new Dimension(640,480));
    GridBagConstraints gbc = new GridBagConstraints();

    gbc.gridx = 10;
    gbc.gridy = 10;
    gbc.weightx = 0;
    add(label1, gbc);

    gbc.gridx = 20;
    gbc.gridy = 10;
    add(label2, gbc);
}

I changed all the gridx, gridy, GridBagConstraints to align them but nothing is working. NORTHEAST for grid constraints is not working either. Can anyone help? Learning how to create my own GUI..

Main coding is here

public static void main(String[] args) {
    JFrame frame = new JFrame("Title111111111");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTabbedPane tp = new JTabbedPane();

    tp.addTab("Intro", new IntroPanel());
    tp.addTab("Catalogue", new CataloguePanel());

    JPanel panel = new JPanel();
    panel.setBackground(Color.WHITE);

    frame.add(panel);
    frame.add(tp);
    frame.pack();

    frame.setVisible(true);
}

Solution

  • The line

    add(label1, gbc);
    

    is adding to this (the IntroPanel).

    What you probably mean is this:

    intro.add(label1, gbc);
    

    EDIT:

    Try adding setLayout(new GridBagLayout()); before the adds