简体   繁体   中英

How to show multiple JPanels with GridLayout buttons inside

I'm trying to create something super basic but after getting super frustrated I figured it was time to ask here.

Desired result:

https://i.stack.imgur.com/0LfGV.png

Right now here is my code:

GUI class

    package bookingProject;

import java.awt.Color;
import javax.swing.JPanel;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;

public class GUI extends javax.swing.JFrame {

    JFrame frame = new JFrame();
    JPanel silverPanel = new JPanel();
    JPanel goldPanel = new JPanel();
    Button buttons[] = new Button[30];

    public static void main(String args[]) {
        new GUI();
    }

    public GUI() {
        setSize(500, 500);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel bronzePanel = new JPanel();
        bronzePanel.setLayout(new GridLayout(3, 10));
        bronzePanel.setBackground(Color.red);
        for (int i = 0; i < 30; i++) {
            buttons[i] = new Button();
            bronzePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            bronzePanel.add(buttons[i]);
        }
        add(bronzePanel);
        setVisible(true);

        silverPanel.setLayout(new GridLayout(3, 10));
        silverPanel.setBackground(Color.yellow);
        for (int i = 0; i < 30; i++) {
            buttons[i] = new Button();
            silverPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            silverPanel.add(buttons[i]);
        }
        add(silverPanel);
        setVisible(true);

        goldPanel.setLayout(new GridLayout(3, 10));
        goldPanel.setBackground(Color.green);
        for (int i = 0; i < 30; i++) {
            buttons[i] = new Button();
            goldPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            goldPanel.add(buttons[i]);
        }
        add(goldPanel);
        setVisible(true);
    }

}

And a class for the Buttons I want to use

Button class

    package bookingProject;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Button extends JButton implements ActionListener{
    public Button (){
    this.addActionListener(this);
}

    public void actionPerformed(ActionEvent e){
        Object source = e.getSource();
        if (source instanceof GUI){
            ((GUI)source).setBackground(Color.YELLOW);
        }
}
}

This is what I'm getting:

https://i.stack.imgur.com/uu9SO.png

I'm brand new to this stuff so forgive my complete ignorance/ability... but what I would like is 3 panels going top to bottom (bronze/silver/gold) each with a GridLayout of buttons... But all I can get is the bronze panel sticking infront of everything else. I think I'm supposed to use BoxLayout to sort the 3 panels into an order but I played around with this for about 4 hours and felt like I was getting nowhere fast.

I also need a way of making the buttons turn yellow when I press them but currently that isn't working; although I barely looked at that.

This is what I'm getting:

By default the content pane of a JFrame uses a BorderLayout . When you add components to the frame the components get added to the BorderLayout.CENTER by default because you didn't specify a constraint. Only one component can be displayed in the CENTER so only the last one added is visible.

I think I'm supposed to use BoxLayout

That is one approach (but probably not the easiest) as you would manually need to specify the space between each row of components.

The section from the Swing tutorial on How to Use Box Layout has a working example to get you started.

Easiest is to use a GridLayout with 3 rows and 2 columns as the layout manager for the frame. Then each individual panel can also use a GridLayout with 3 rows and 5 columns.

If you want spaces between the components in each of your panels then you need to look at the GridLayout API. It allows you to specify a vertical and horizontal gap between components.

Another approach would be to use a GridBagLayout , although this is a little more complicated because you need to specify constraints for each component added.

The tutorial also has sections on How to Use GridBag Layout and How to Use GridLayout .

Note the examples from the tutorial will also show you how to better structure your code so that component are created on the Event Dispatch Thread(EDT).

You can try GridBagLayout instead:

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import java.awt.Insets;
import java.awt.Color;
class Demo{
    public static void main(String[]args){
        SwingUtilities.invokeLater(()->{
            JFrame frame=new JFrame("Grid");
            JPanel panel=(JPanel)frame.getContentPane();
            GridBagConstraints gbc=new GridBagConstraints();
            gbc.insets=new Insets(9,7,5,5);
            panel.setLayout(new GridBagLayout());

            panel.add(newGrid(Color.YELLOW,gbc, 0, 0),gbc);
            panel.add(newGrid(Color.YELLOW,gbc, 1, 0),gbc);

            panel.add(newGrid(Color.LIGHT_GRAY,gbc, 0, 1),gbc);
            panel.add(newGrid(Color.LIGHT_GRAY,gbc, 1, 1),gbc);

            panel.add(newGrid(Color.GREEN,gbc, 0, 2),gbc);
            panel.add(newGrid(Color.GREEN,gbc, 1, 2),gbc);

            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        });
    }
    private static JPanel newGrid(Color color, GridBagConstraints pGbc, int pX, int pY){
        JPanel panel=new JPanel(new GridBagLayout());
        GridBagConstraints gbc=new GridBagConstraints();
        gbc.insets=new Insets(5,5,5,5);
        for(int x=0;5>x;x++){
            for(int y=0;3>y;y++){
                gbc.gridx=x;
                gbc.gridy=y;
                JButton btn=new JButton("<html>&nbsp;</html>");
                btn.setBackground(color);
                panel.add(btn,gbc);
            }
        }
        pGbc.gridx=pX;
        pGbc.gridy=pY;
        return panel;
    }
}

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM