3

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

                setLayout(new GridLayout(rows, cols));
                for(int i = 0; i < rows; i++)
                for(int j = 0; j < cols; j++)
            {
                goldSeat = new JButton();
                silverSeat = new JButton();
                bronzeSeat = new JButton();
                add(new JButton());
            }
                this.add(Panel1);

       }
}

at the minute I'm just getting 30 buttons in the jpanel, where they are not in rows or columns? help :(

4
  • 1
    You're creating a goldSeat, a silverSeat, and a bronzeSeat, and you're doing nothing with them -- you're not adding them to the GUI. You then create another JButton and do add it to the GUI -- why? This doesn't make sense. Again you're also adding a blank JPanel to the GridLayout using JPanel -- again why? Explain please what you're trying to do. Nov 25, 2016 at 23:10
  • I have to create a booking system, where there are a set of gold seats, silver seats and bronze seats. there are three rows for each colour of seats, each row containing 10 seats (30 gold seats, 30 silver and 30 bronze). A seat in going to be a JButton, and here I am trying to get the layout of the seats to be in rows and columns.
    – May
    Nov 25, 2016 at 23:17
  • 1
    The issue though is, if you create a JButton, you need to add it to the ConcertPanel by calling its add(...) method, else you're just spinning your wheels -- make sense? Nov 25, 2016 at 23:19
  • Please see edits to answer. Been experimenting with the code some. Nov 26, 2016 at 0:14

1 Answer 1

6

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

EDIT

See comments for problems with this code:

    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++) {
            goldSeat = new JButton();   // button created but never added
            silverSeat = new JButton(); // button created but never added
            bronzeSeat = new JButton(); // button created but never added
            add(new JButton()); // only button added
        }
    this.add(Panel1); // this throws off the whole GridLayout since it's added to the grid

So within our nested for loop, you create 3 JButtons, but since they never get added to the GUI, they serve no purpose and in fact will be garbage collected, all but the last 3 created. You then create a button and do add it. Finally you create a JPanel but add it to the GridLayout-using JPanel, which will throw the grid off.


Having more fun with this code:

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;

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

    public GridLayoutEg() {
        int gap = 1;
        int gap2 = 2;
        setBorder(BorderFactory.createEmptyBorder(gap2, gap2, gap2, gap2));
        setLayout(new GridLayout(ROWS, COLS, gap, gap)); // set JPanel's layout
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                JButton button = createSeat(row, col);
                add(button); // add component w/o a 2nd parameter
            }
        }
    }

    private JButton createSeat(int row, int col) {
        SeatColor seatColor = SeatColor.values()[row];
        SeatAction seatAction = new SeatAction(seatColor, col);
        JButton button = new JButton(seatAction);
        button.setBackground(seatColor.getColor());
        int topGap = 8;
        int sideGap = 25;
        Border innerBorder = BorderFactory.createEmptyBorder(topGap, sideGap, topGap, sideGap);
        Border outerBorder = BorderFactory.createBevelBorder(BevelBorder.RAISED, seatColor.getColor().brighter(),
                seatColor.getColor().darker());
        Border border = BorderFactory.createCompoundBorder(outerBorder, innerBorder);
        button.setBorder(border);
        return button;
    }

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

class SeatAction extends AbstractAction {
    private static final long serialVersionUID = 1L;
    private SeatColor seatColor;
    private int column;

    public SeatAction(SeatColor seatColor, int column) {
        super(String.format("[%d]", column));
        this.seatColor = seatColor;
        this.column = column;
        // putValue(LARGE_ICON_KEY, createIcon(seatColor, column));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        AbstractButton btn = (AbstractButton) e.getSource();
        btn.setBackground(seatColor.getColor().brighter());
        setEnabled(false);

        String text = String.format("Selected Seat Color: %s; Column: %d", seatColor, column);
        System.out.println(text );
    }
}

enum SeatColor {
    GOLD("Gold", new Color(255, 215, 0)), 
    SILVER("Silver", new Color(192, 192, 192)), 
    BRONZE("Bronze", new Color(205, 127, 50));

    private String text;
    private Color color;

    private SeatColor(String text, Color color) {
        this.text = text;
        this.color = color;
    }

    public String getText() {
        return text;
    }

    public Color getColor() {
        return color;
    }

    @Override
    public String toString() {
        return getText();
    }

}
2
  • Trying to use your code as a guidline it does give me out 30 JButtons however it doesnt give me them in the rows and columns.. This is what I've done now. ps you can tell I am not good at coding - setLayout(new GridLayout(rows, cols)); for(int i = 0; i < rows; i++) for(int j = 0; j < cols; j++) { goldSeat = new JButton(); silverSeat = new JButton(); bronzeSeat = new JButton(); add(new JButton()); }
    – May
    Nov 25, 2016 at 22:53
  • @May: hello! Unfortunately code does not show well in comments. If you're still stuck, please edit your original question showing the new code and problems with it at the bottom. It looks like you're creating a bunch of (4) buttons and only adding the last one to the GUI, which looks a little confusing. Please clarify by editing your post. Nov 25, 2016 at 23:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.