I know there have been several posts already about Sudoku-related questions, but I am not sure any of them have exactly what I am looking for...
I am trying to build an empty Sudoku board in Java using JPanels and JTextfields. I also need to create a menu on the right hand side with another JPanel.
The board itself is a 9 x 9 square, divided into 9 3x3 squares. Note that each smaller square is set off by a heavier border than the regular intersquare borders. Each square is a text field. Write the program so that nothing is in a text field. Users can type in the text field if they want, and if they do, numbers will show up. On the side there are four buttons that allow you to solve, get a new puzzle, get a hint, or reset puzzle.
Any ideas would be great. I am having trouble understanding how to nest the for loops to create the board. Here is my code...
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
public class ArrayTest extends JFrame {
public ArrayTest() {
JPanel board = new JPanel(new GridLayout(9, 9));
add(board);
JPanel[][] squares = new JPanel[9][9];
Border border = BorderFactory.createLineBorder(Color.BLACK);
for (int row = 1; row < 9; row++) {
for (int col = 1; col < 9; col++) {
squares[row][col] = new JPanel();
board.add(squares[row][col]);
}
}
JPanel menu = new JPanel();
menu.add(new JButton("Reset"));
menu.add(new JButton("Hint"));
menu.add(new JButton("Solve"));
menu.add(new JButton("New Puzzle"));
add(menu);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
/** Create a frame and set its properties*/
JFrame frame = new ArrayTest();
frame.setTitle("Sudoku");
frame.setSize(600, 600);
frame.setLocationRelativeTo(null); //Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
A couple of things I see:
I don't think you want 9x9 JPanel
s as you have now, but 9x9 JTextField
s. You may want 3x3 JPanel
s so you can make the borders of each section bolder. It might be easier to just lay these out explicitly instead of trying to do it in a loop.
Your loop counters (and array indices) should start at 0, not 1. The way you have it now, the loops will only execute 8 times.
You are going to want to keep track of values in each row, column, and in each 3x3 sub-group. Rows and columns are easy the way you have it in a 2D array. You might consider another array of arrays that hold the values in each 3x3 area. This makes it easier to scan through these values when you need to, and might be useful for placing values in the smaller 3x3 JPanel
s, if you go that route.