Java Swing How to - Make a simple column of buttons down the west JPanel with BorderLayout and GridLayout








Question

We would like to know how to make a simple column of buttons down the west JPanel with BorderLayout and GridLayout.

Answer

import java.awt.BorderLayout;
import java.awt.GridLayout;
/*from w  w w . j  a  v  a 2  s  . c o  m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {

  public static void main(String[] args) {
    JLabel label = new JLabel("java2s.com");

    JFrame frame = new JFrame("Testing");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.add(label);

    JPanel buttons = new JPanel(new GridLayout(0, 1));
    for (int index = 0; index < 10; index++) {
      buttons.add(new JButton(String.valueOf(index)));
    }

    JPanel right = new JPanel(new BorderLayout());
    right.add(buttons, BorderLayout.NORTH);
    frame.add(right, BorderLayout.EAST);

    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}