显示 JLabel 矩阵

Displaying JLabel matrix

有人能告诉我为什么在调用方法 getContentPane().add(grid[i][j]) 后我无法显示 JLabel 的矩阵。仅显示一个 "e" 个标签。

public class SudokuFrame 扩展 JFrame 实现 ActionListener {

JButton generateButton;
JLabel[][] grid;

public SudokuFrame(){
    setSize(300, 300);
    setTitle("Sudoku");
    setLayout(null);
    generateButton = new JButton("Generate");
    generateButton.setBounds(90, 220, 100, 30);
    add(generateButton);
    generateButton.addActionListener(this);

    grid = new JLabel[9][9];
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            grid[i][j] = new JLabel("e");
            grid[i][j].setBounds(100, 100, 30, 30);
            getContentPane().add(grid[i][j]);
        }
    }
}

public static void main(String[] args){
    SudokuFrame frame = new SudokuFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

您为每个 JLabel 赋予了 完全相同的边界 -- 相同的大小和相同的位置,因此每个新标签都被放置在先前添加的标签之上。

解决方法:不要使用空布局。当问题完全适合 GridLayout 时,为什么要使用它?通常,您希望避免使用空布局和 setBounds,因为布局管理器将使您的编码和 GUI 更易于管理。让布局为您完成繁重的工作。

例如,

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.*;

public class SimpleSudoku extends JPanel {
    private static final int GAP = 1;
    private static final Font LABEL_FONT = new Font(Font.DIALOG, Font.PLAIN, 24);
    private JLabel[][] grid = new JLabel[9][9];

    public SimpleSudoku() {
        JPanel sudokuPanel = new JPanel(new GridLayout(9, 9, GAP, GAP));
        sudokuPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        sudokuPanel.setBackground(Color.BLACK);
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                grid[row][col] = new JLabel("     ", SwingConstants.CENTER);
                grid[row][col].setFont(LABEL_FONT); // make it big
                grid[row][col].setOpaque(true);
                grid[row][col].setBackground(Color.WHITE);
                sudokuPanel.add(grid[row][col]);
            }
        }

        JPanel bottomPanel = new JPanel();
        bottomPanel.add(new JButton("Regenerate"));

        setLayout(new BorderLayout());
        add(sudokuPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

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

    private static void createAndShowGui() {
        SimpleSudoku mainPanel = new SimpleSudoku();
        JFrame frame = new JFrame("SimpleSudoku");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
}