Skip to content

Instantly share code, notes, and snippets.

@R3DHULK
Created May 21, 2023 08:46
Show Gist options
  • Save R3DHULK/c3eb4d22e4af74781e2598804e6508fc to your computer and use it in GitHub Desktop.
Save R3DHULK/c3eb4d22e4af74781e2598804e6508fc to your computer and use it in GitHub Desktop.
Sudoku Game Board In Java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SudokuGame extends JFrame {
private static final int GRID_SIZE = 9;
private static final int CELL_SIZE = 60;
private static final int BOARD_SIZE = GRID_SIZE * CELL_SIZE;
private static final int[][] BOARD = {
{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}
};
private JTextField[][] textFields;
public SudokuGame() {
setTitle("Sudoku");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLayout(new GridLayout(GRID_SIZE, GRID_SIZE));
textFields = new JTextField[GRID_SIZE][GRID_SIZE];
// Create and initialize the text fields
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
textFields[row][col] = new JTextField();
textFields[row][col].setHorizontalAlignment(JTextField.CENTER);
textFields[row][col].setFont(new Font("Arial", Font.BOLD, 20));
textFields[row][col].setPreferredSize(new Dimension(CELL_SIZE, CELL_SIZE));
add(textFields[row][col]);
}
}
// Set the initial values on the text fields
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
if (BOARD[row][col] != 0) {
textFields[row][col].setText(String.valueOf(BOARD[row][col]));
textFields[row][col].setEditable(false);
}
}
}
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SudokuGame().setVisible(true);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment