显示JLabel矩阵

时间:2016-04-17 19:38:42

标签: java swing jlabel

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

public class SudokuFrame extends 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);
}

1 个答案:

答案 0 :(得分:4)

你给每个JLabel 完全相同的边界 - 相同的大小和相同的位置,所以每个新的标签都放在以前添加的标签之上。

解决方案:不要使用null布局。当问题非常适合GridLayout时,为什么要使用它?通常,您希望避免使用null布局和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);
    }
}