I’m trying to get second cell width to be 2 but some weird reason GridBagLayout is making first cell width to be 2 instead of second cell. How do I fix this?
Here’s my code:
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.*;
public class LearnGridBagLayout {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(800,600);
JPanel panel = new JPanel();
GridBagLayout gridbaglayout = new GridBagLayout();
panel.setLayout(gridbaglayout);
frame.setContentPane(panel);
JButton button = new JButton("Hello World!");
GridBagConstraints gridbagconstraints = new GridBagConstraints();
gridbagconstraints.fill = GridBagConstraints.BOTH;
gridbagconstraints.weightx = 1;
gridbagconstraints.weighty = 1;
gridbagconstraints.gridx = 0;
gridbagconstraints.gridy = 0;
gridbagconstraints.gridwidth = 1;
gridbagconstraints.gridheight = 1;
panel.add(button,gridbagconstraints);
JButton input = new JButton();
GridBagConstraints gridbagconstraints2 = new GridBagConstraints();
gridbagconstraints2.fill = GridBagConstraints.BOTH;
gridbagconstraints2.weightx = 1;
gridbagconstraints2.weighty = 1;
gridbagconstraints2.gridwidth=2;
gridbagconstraints2.gridheight=1;
gridbagconstraints2.gridx = 1;
gridbagconstraints2.gridy=0;
panel.add(input,gridbagconstraints2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I’m trying to get both cells to fill whole width and second cell to be with width length 2.
New contributor
Matthew Perkovic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.