How to create vertical button column with GridLayout in Java?

Java 8Object Oriented ProgrammingProgramming

To create a vertical button column, let us first create some buttons and set the layout as well −

JPanel btnPanel = new JPanel(new GridLayout(10, 1, 10, 5));
btnPanel.add(new JButton("First Button"));
btnPanel.add(new JButton("Second Button"));
btnPanel.add(new JButton("Third Button"));
btnPanel.add(new JButton("Fourth Button"));
btnPanel.add(new JButton("Fifth Button"));
btnPanel.add(new JButton("Sixth Button"));
btnPanel.add(new JButton("Seventh Button"));
btnPanel.add(new JButton("Eighth Button"));

Above, we have set the GridLayout to create rows and columns with vertical and horizontal gap.

The following is an example to create vertical button column with GridLayout −

Example

package my;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JPanel panel = new JPanel(new BorderLayout());
      panel.setBorder(new EmptyBorder(2, 3, 2, 3));
      JPanel layout = new JPanel(new GridBagLayout());
      layout.setBorder(new EmptyBorder(5, 5, 5, 5));
      JPanel btnPanel = new JPanel(new GridLayout(10, 1, 10, 5));
      btnPanel.add(new JButton("First Button"));
      btnPanel.add(new JButton("Second Button"));
      btnPanel.add(new JButton("Third Button"));
      btnPanel.add(new JButton("Fourth Button"));
      btnPanel.add(new JButton("Fifth Button"));
      btnPanel.add(new JButton("Sixth Button"));
      btnPanel.add(new JButton("Seventh Button"));
      btnPanel.add(new JButton("Eighth Button"));
      layout.add(btnPanel);
      panel.add(layout, BorderLayout.CENTER);
      JFrame frame = new JFrame("Demo");
      frame.add(panel);
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.setLocationByPlatform(true);
      frame.setSize(500, 400);
      frame.setVisible(true);
   }
}

Output


raja
Published on 03-Jun-2019 15:04:13
Advertisements