Java Swing How to - Create vertical button column with GridLayout








Question

We would like to know how to create vertical button column with GridLayout.

Answer

import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
/*  ww  w .j  a v a 2  s . c  o m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;

public class Main {

  public static void main(String[] args) {
    JPanel gui = new JPanel(new BorderLayout());
    gui.setBorder(new EmptyBorder(2, 3, 2, 3));

    JPanel textPanel = new JPanel(new BorderLayout(5, 5));
    textPanel.add(new JScrollPane(new JTextArea("Top Text", 3, 20)),
        BorderLayout.PAGE_START);
    textPanel.add(new JScrollPane(new JTextArea("Main Text", 10, 10)));
    gui.add(textPanel, BorderLayout.CENTER);

    JPanel buttonCenter = new JPanel(new GridBagLayout());
    buttonCenter.setBorder(new EmptyBorder(5, 5, 5, 5));
    JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 5, 5));
    for (int ii = 1; ii < 6; ii++) {
      buttonPanel.add(new JButton("Button " + ii));
    }

    buttonCenter.add(buttonPanel);

    gui.add(buttonCenter, BorderLayout.LINE_END);

    JFrame f = new JFrame("Demo");
    f.add(gui);

    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    f.setLocationByPlatform(true);

    f.pack();

    f.setVisible(true);
  }
}