May May - 7 days ago 7
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

JButtons
) 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;


ConcertPanel()
{
Panel1 = new JPanel();
Panel1.setSize(500,500);

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

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));

this.add(Panel1);

}
}


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

Answer

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");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
}
Comments