May May - 1 year ago 112
Java Question

Creating rows and columns of JButtons

I have been given a task to create 3 sets of seats, and each set has 3 rows and 10 columns of seats. Firstly to get started I created one seat each for the three sets and I'm now trying to use the layout manager to display the seats(which are

) in the style 3x10. Here's the code I have:

public class ConcertPanel extends JPanel
private JPanel Panel1;
private JButton goldSeat;
private JButton silverSeat;
private JButton bronzeSeat;

Panel1 = new JPanel();

goldSeat = new JButton();
setLayout(new GridLayout(int rows,int cols));

silverSeat = new JButton("");
setLayout(new GridLayout(int rows, int cols));
this.add(silverSeat, GridLayout(3,10);

bronzeSeat = new JButton("");
setLayout(new GridLayout(int rows, int cols));
this.add(bronzeSeat, GridLayout(3,10));



Can anyone tell me why
wouldn't be working or how do i get the buttons to be in rows and columns?

Answer Source

Please have another look at the GridLayout tutorial:

  • You want to set the GridLayout to the container once.
  • You add your component (JButton) without a 2nd parameter when adding with GridLayout.
  • If the layout should be 3 x 10, you'll want to add 30 components to this container.
  • You're adding another JPanel,panel1, to the GridLayout-using JPanel, and it will become part of the grid. It doesn't seem like you want to do this.

For example:

Example GUI

import java.awt.GridLayout;

import javax.swing.*;

public class GridLayoutEg extends JPanel {
    private static final int ROWS = 3;
    private static final int COLS = 10;

    public GridLayoutEg() {
        setLayout(new GridLayout(ROWS, COLS)); // set JPanel's layout
        for (int i = 0; i < ROWS; i++) {
            for (int j = 0; j < COLS; j++) {
                String text = String.format("[%d, %d]", j + 1, i + 1);
                add(new JButton(text)); // add component w/o 2nd parameter

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());

    private static void createAndShowGui() {
        GridLayoutEg mainPanel = new GridLayoutEg();
        JFrame frame = new JFrame("GridLayoutEg");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download