javajbuttonlayout-managerjappletgridbaglayout

Resize buttons using Grid Bag Layout


I want to resize my buttons to be the same size and place then in a Panel on a JApplet. I have tried using

public void init() {
    // TODO start asynchronous download of heavy resources

    JButton btnWestern=new JButton("Western");
    JButton btnPop=new JButton("Pop");

    GridBagConstraints c4=new GridBagConstraints();

    JPanel jPanel1 = new JPanel();
    getContentPane().setLayout(new java.awt.GridBagLayout());
    jPanel1.setLayout(new java.awt.GridBagLayout());

    c4.gridx = 0;
    c4.gridy = 0;
    c4.insets = new Insets(36, 10, 0, 249);
    jPanel1.add(btnWestern, c4);

    c4.gridx = 0;
    c4.gridy = 1;
    c4.insets = new Insets(33, 10, 0, 249);
    jPanel1.add(btnPop, c4);

    add(jPanel1, new java.awt.GridBagConstraints());

    }

When I run, this is what I get

enter image description here

But I noticed that if I change the button text to be the same or have the same length, like

JButton btnWestern=new JButton("Button1");
JButton btnPop=new JButton("Button2");

I get the desired output

enter image description here

What can I do to make sure that even the text of the buttons are not the same length, the buttons are the same size?


Solution

  • I'd suggest reading through the How to Use GridBagLayout tutorial if you haven't already. GridBagLayout is powerful but it is also one of the more complex LayoutManagers available.

    I believe you need to set the GridBagConstraints.fill property to get the behavior you desire.

    In your case this should be something like

    c4.fill = GridBagConstraints.HORIZONTAL;

    Edit (A bit of explanation for the observed behavior) When you use the same text on both buttons, their calculated size ends up being the same, so they are rendered as you want. When you use different size text, the buttons will render in a size that fits the text by default. The default value for GridBagConstraints.fill is GridBagConstraints.NONE which indicates to the LayoutManger to not resize the component. Changing the fill to GridBagConstraints.HORIZONTAL tells the LayoutManger to resize the component horizontally to fill the display area.