SAE21_2024/VerifButton.java

104 lines
3.5 KiB
Java

import javax.swing.*;
import java.awt.event.*;
import java.awt.Color;
public class VerifButton implements ActionListener {
private int GRID_SIZE;
private JTextField[][] grid;
public VerifButton(int GRID_SIZE, JTextField[][] grid) {
this.GRID_SIZE = GRID_SIZE;
this.grid = grid;
}
@Override
public void actionPerformed(ActionEvent e) {
if (grilleValide()) {
JOptionPane.showMessageDialog(null, "La grille est valide.", "Validation", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "La grille n'est pas valide.", "Erreur", JOptionPane.ERROR_MESSAGE);
}
}
private boolean grilleValide() {
for (int row = 0; row < this.GRID_SIZE; row++) {
for (int col = 0; col < this.GRID_SIZE; col++) {
if (!grid[row][col].getText().isEmpty()) {
int evaluant = Integer.parseInt(grid[row][col].getText());
// Test de validité sur les lignes
for (int row2 = row + 1; row2 < this.GRID_SIZE; row2++) {
if (!grid[row2][col].getText().isEmpty()) {
int comparateur = Integer.parseInt(grid[row2][col].getText());
if (evaluant == comparateur) {
grid[row2][col].setBackground(Color.red);
grid[row][col].setBackground(Color.red);
return false;
}
}
}
for (int row2 = row - 1; row2 >= 0; row2--) {
if (!grid[row2][col].getText().isEmpty()) {
int comparateur = Integer.parseInt(grid[row2][col].getText());
if (evaluant == comparateur) {
grid[row2][col].setBackground(Color.red);
grid[row][col].setBackground(Color.red);
return false;
}
}
}
// Test de validité sur les colonnes
for (int col2 = col + 1; col2 < this.GRID_SIZE; col2++) {
if (!grid[row][col2].getText().isEmpty()) {
int comparateur = Integer.parseInt(grid[row][col2].getText());
if (evaluant == comparateur) {
grid[row][col2].setBackground(Color.red);
grid[row][col].setBackground(Color.red);
return false;
}
}
}
for (int col2 = col - 1; col2 >= 0; col2--) {
if (!grid[row][col2].getText().isEmpty()) {
int comparateur = Integer.parseInt(grid[row][col2].getText());
if (evaluant == comparateur) {
grid[row][col2].setBackground(Color.red);
grid[row][col].setBackground(Color.red);
return false;
}
}
}
// Vérifier la validité dans les régions
int rowregion = row/3*3;
int colregion = col/3*3;
for (int row2 = rowregion; row2 < rowregion + 3; row2++) {
for (int col2 = colregion; col2 < colregion + 3; col2++) {
if (row2 != row && col2 != col ) {
if (!grid[row2][col2].getText().isEmpty()) {
int comparateur = Integer.parseInt(grid[row2][col2].getText());
if (evaluant == comparateur) {
grid[row2][col2].setBackground(Color.red);
grid[row][col].setBackground(Color.red);
return false;
}
}
}
}
}
}
}
}
return true;
}
}