Search code examples
javaswingpositiongridbaglayout

How to bring JLabels in GridBagConstrains at top


I was trying this code, and for some reason, it appears in the middle. Here's my code:

        String errormsg = "Something went wrong."; 
    final String title = "Wall Game";

    this.setSize(400, 500); //sets the screen
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle(title);
    this.setVisible(true);
    this.setSize(401,501);
    try {
        Font font1 = new Font("Comic Sans MS", Font.BOLD, 15);
        JPanel panel1 = new JPanel(new GridBagLayout()); //makes all the panels
        JLabel label1 = new JLabel("Welcome to the Wall Game!"); //labels
        JLabel label2 = new JLabel("Click the button to read instructions!");
        JButton button1 = new JButton("Start");//buttons
        button1.setText("Start!");
        label1.setFont(font1);
        button1.setLayout(new BoxLayout(button1, BoxLayout.Y_AXIS));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(15,10,10,10);

        gbc.gridx = 0;
        gbc.gridy = 0;
        panel1.add(label1, gbc);
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel1.add(label2, gbc);
        gbc.gridx = 0;
        gbc.gridy = 2;
        panel1.add(button1, gbc);
        this.add(panel1);
    }
    catch(Exception e) { 
        JOptionPane.showMessageDialog(null, "Something went wrong. Try restarting.", "Sorry", JOptionPane.INFORMATION_MESSAGE);
    }
}

Where the text shows is in the middle. Not starting from the top. Here's a mini example of what it would look like:

enter image description here

Does anyone know how to make the starting point from the top? Thanks to anyone who can help. Before you try helping, try the code first. You, will definitely need import "javax.swing.*" FYI.

Thumbs up if you like the paint drawing I did lol :D I drew it in Window's paint.


Solution

  • Read the section from the Swing tutorial on How to Use GridBag Layout, especially the section on the weightx/y constraints.

    You need to have a non-zero value set for one of the components otherwise the components are centered.