到目前为止,我已经编写了生成9x9随机Soduku网格的代码。我是Java的初学者,所以我对如何使用UI有一些疑问。
显示数字的最佳方法是什么?我尝试创建81个JTextField,这非常繁琐,而且我确信有一种有效的方法可以做到这一点。也许将jtextfields存储在数组中?还是我应该使用与jtextfields不同的东西?
创建网格线的最佳方法是什么?我有一些不同的想法,但是可能没有那么复杂的方法。
最佳答案
考虑使用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);
}
}