Java Swing How to - Align buttons to the middle-right with GridBagLayout








Question

We would like to know how to align buttons to the middle-right with GridBagLayout.

Answer

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
/*from  ww  w  .  j a  v  a 2 s  .com*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {

  private JPanel contentPane;

  public static void main(String[] args) {
    Main frame = new Main();
    frame.setVisible(true);
  }

  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    contentPane = new JPanel();

    setContentPane(contentPane);
    GridBagLayout gbl_panel = new GridBagLayout();
    gbl_panel.columnWidths = new int[] { 0, 0, 0, 0 };
    gbl_panel.rowHeights = new int[] { 0, 0, 0, 0, 0, 0 };
    gbl_panel.columnWeights = new double[] { 0.0, 0.1, 0.0, Double.MIN_VALUE };
    gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0,
        Double.MIN_VALUE };

    contentPane.setLayout(gbl_panel);

    JButton btn_1 = new JButton("B1");
    GridBagConstraints gbc_comboBox = new GridBagConstraints();
    gbc_comboBox.insets = new Insets(0, 0, 5, 20);
    gbc_comboBox.gridx = 2;
    gbc_comboBox.gridy = 0;
    gbc_comboBox.weightx = 0.0;
    contentPane.add(btn_1, gbc_comboBox);

    JButton btn_2 = new JButton("B2");
    GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
    gbc_btnNewButton.insets = new Insets(0, 0, 5, 20);
    gbc_btnNewButton.gridx = 2;
    gbc_btnNewButton.gridy = 1;
    contentPane.add(btn_2, gbc_btnNewButton);
    setSize(200, 300);
  }

}