如何使用BoxLayout制作5x5布局?

时间:2019-04-07 17:03:09

标签: java swing user-interface layout-manager

我正在创建一个Bingo GUI,但在格式化/创建布局时遇到了一些问题。我需要将其设置为5x5的按钮布局(就像宾果卡一样),但是我似乎不明白如何使用BOXLAYOUT来做到这一点。还是我以错误的方式添加了按钮? Java GUI的新手。

我尝试同时使用X和Y轴,但它不起作用。它将以水平或垂直线(如x和y轴)显示所有按钮

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import java.util.Random;

public class swingBoxLayoutAlignment {

    public static void main(String[] args) {
        // Create and set up a frame window
        JFrame frame = new JFrame("Bingo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton[][] btn1 = new JButton[5][5];
        Random rnd = new Random();

        // Declaring values for the button
        for (int i = 0; i < 5; i++) {
            for (int col = 0; col < 5; col++) {
                btn1[i][col] = new JButton(Integer.toString(rnd.nextInt(15) + 1 + i * 15));
                btn1[i][col].addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        JButton btn1 = (JButton) e.getSource();
                    }
                });
            }
        }
        JPanel panel1 = new JPanel();
        panel1.setBorder(BorderFactory.createTitledBorder("PLAYER CARDS"));

        BoxLayout layout1 = new BoxLayout(panel1, BoxLayout.X_AXIS); //This is where im having some trouble)
        panel1.setLayout(layout1);

        for(int m = 0; m < 5; m++){
            panel1.add(btn1[m][0]);
            panel1.add(btn1[m][1]);
            panel1.add(btn1[m][2]);
            panel1.add(btn1[m][3]);
            panel1.add(btn1[m][4]);
            btn1[2][2].setBackground(Color.YELLOW);
        }
        frame.setLayout(new FlowLayout());
        frame.add(panel1);
        frame.pack();
        frame.setVisible(true);
    }
}

0 个答案:

没有答案