简体   繁体   English

如何为我的数独游戏制作 GUI? (摇摆)

[英]How do I make a GUI for my Sudoku game? (Swing)

So far, I've written the code that generates a random 9x9 Soduku grid.到目前为止,我已经编写了生成随机 9x9 Soduku 网格的代码。 I'm a beginner in Java, so I have a few questions about how to do the UI.我是 Java 的初学者,所以我有一些关于如何做 UI 的问题。

  1. What's the best way to display the numbers?显示数字的最佳方式是什么? I tried creating 81 JTextFields which was extremely tedious, and I'm sure there's an efficient way to do this.我尝试创建 81 个 JTextFields,这非常乏味,我相信有一种有效的方法可以做到这一点。 Maybe storing the jtextfields in an array?也许将 jtextfields 存储在一个数组中? Or should I use something different than jtextfields?或者我应该使用与 jtextfields 不同的东西?

  2. What's the best way to create the grid lines?创建网格线的最佳方法是什么? I have a few different ideas but there are probably less complicated ways.我有一些不同的想法,但可能有不那么复杂的方法。

Consider using a 9x9 array of JLabel s:考虑使用JLabel的 9x9 数组:

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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