SAE21_2023/SudokuButtonListener.java

73 lines
2.4 KiB
Java
Raw Normal View History

2024-04-28 01:40:14 +02:00
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SudokuButtonListener implements ActionListener {
private int row;
private int col;
2024-04-30 12:20:16 +02:00
private Grid grid;
2024-04-28 01:40:14 +02:00
private JButton[][] buttons;
2024-04-30 12:20:16 +02:00
public SudokuButtonListener(int row, int col, Grid grid, JButton[][] buttons) {
2024-04-28 01:40:14 +02:00
this.row = row;
this.col = col;
2024-04-30 12:20:16 +02:00
this.grid = grid;
2024-04-28 01:40:14 +02:00
this.buttons = buttons;
}
@Override
public void actionPerformed(ActionEvent e) {
2024-04-30 12:20:16 +02:00
try {
int num = Integer.parseInt(JOptionPane.showInputDialog("Enter a number:"));
grid.getCell(row, col).setValue(num);
if (num == 0) {
buttons[row][col].setText(""); // Empty cell if the number is 0
} else {
buttons[row][col].setText(String.valueOf(num));
2024-04-28 01:40:14 +02:00
}
2024-04-30 12:20:16 +02:00
if (!isValidMove(num, row, col)) {
buttons[row][col].setForeground(Color.RED); // Set text color to red for invalid move
} else {
buttons[row][col].setForeground(Color.BLACK); // Reset text color
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Please enter a valid number.");
2024-04-28 01:40:14 +02:00
}
}
private boolean isValidMove(int num, int row, int col) {
return isValidRow(num, row) && isValidCol(num, col) && isValidBox(num, row - row % 3, col - col % 3);
}
private boolean isValidRow(int num, int row) {
for (int i = 0; i < 9; i++) {
2024-04-30 12:20:16 +02:00
if (grid.getCell(row, i).getValue() == num && i != col) {
2024-04-28 01:40:14 +02:00
return false;
}
}
return true;
}
private boolean isValidCol(int num, int col) {
for (int i = 0; i < 9; i++) {
2024-04-30 12:20:16 +02:00
if (grid.getCell(i, col).getValue() == num && i != row) {
2024-04-28 01:40:14 +02:00
return false;
}
}
return true;
}
private boolean isValidBox(int num, int boxStartRow, int boxStartCol) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int row = i + boxStartRow;
int col = j + boxStartCol;
2024-04-30 12:20:16 +02:00
if (grid.getCell(row, col).getValue() == num && (row != this.row || col != this.col)) {
2024-04-28 01:40:14 +02:00
return false;
}
}
}
return true;
}
2024-04-30 12:20:16 +02:00
}