java - 如何为我的数独游戏制作 GUI? ( Swing )

标签 java swing sudoku

到目前为止,我已经编写了生成随机 9x9 Soduku 网格的代码。我是Java初学者,所以我有一些关于如何做UI的问题。

  1. 显示数字的最佳方式是什么?我尝试创建 81 个 JTextFields,这非常乏味,而且我确信有一种有效的方法可以做到这一点。也许将 jtextfields 存储在数组中?或者我应该使用与 jtextfields 不同的东西?

  2. 创建网格线的最佳方法是什么?我有一些不同的想法,但可能有不太复杂的方法。

最佳答案

考虑使用 9x9 的 JLabel 数组:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class Soduko {

    private Cell[][] cells;
    private static final int SIZE = 9, GAP = 2;
    private final JFrame jFrame;

    public Soduko() {

        jFrame = new JFrame("Soduko");
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setLocationRelativeTo(null);
        buildUi();
        jFrame.pack();
        jFrame.setVisible(true);
    }

    void buildUi() {

        JPanel gridPanel = new JPanel();
        gridPanel.setLayout(new GridLayout(SIZE, SIZE, GAP, GAP));
        gridPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        jFrame.add(gridPanel, BorderLayout.CENTER);

        cells = new Cell[SIZE][SIZE];
        Random rand = new Random();
        for(int row=0; row <cells.length; row++) {
            for(int col=0; col<cells[row].length; col++) {
                Cell cell = new Cell(rand.nextInt(SIZE+1)); //initialize with random number for demo
                cells[row][col] = cell;
                gridPanel.add(cell);
            }
        }

        jFrame.add(new JLabel("Help:           "),  BorderLayout.SOUTH);
    }

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

class Cell extends JLabel {

    private static int CELL_H =35, CELL_W = 35;

    Cell(int value) {
        super(String.valueOf(value));
        setHorizontalAlignment(SwingConstants.CENTER);
        setBorder(BorderFactory.createLineBorder(Color.BLUE));
        setPreferredSize(new Dimension(CELL_H , CELL_W));
        setOpaque(true);
    }
}

关于java - 如何为我的数独游戏制作 GUI? ( Swing ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59403203/

相关文章:

java - Swing - 不使用滚动条滚动 JFrame 内容

python - 拼写错误,Python 函数仍然有效。为什么?

prolog 数独求解器耗尽全局堆栈

javascript - 将音频文件/blob 从 UI 发送到 Servlet 以保存在服务器上。

java - 无法完成架构更新 Envers + Firebird

Java 用户在一行中指定输入文件

java - 处理 java 类型

java - 如何制作可滚动 JList 以添加从 JOptionPane 获取的详细信息

java - 设置用作 JTable RowFilter 时 JComboBox 中显示的选项数量

c++ - 数独生成 : it goes in loop