📄 sudokugui.java
字号:
// Name: Tsang Kai Ming, Patrick (25)
// Couse Code 41300/1 Group V
// Subject: ICT-1414 Object-oriented Programming
// Sudoku Assignment 2 File (Java Programming)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class SudokuGUI extends JFrame implements ActionListener, FocusListener {
private JPanel sudokuPanel, inputPanel, buttonPanel;
private JPanel[] gridPanel;
private JTextField[][] sudokuTF;
private Sudoku sudoku, sudokuFilled, sudokuSolution;
private JTextField fileTF;
private JButton loadBtn, hintsBtn, checkBtn, validBtn;
private int focusX=-1, focusY=-1; // position of the focused text field
// The constructor set up the GUI components
public SudokuGUI() {
super("Sudoku");
// Create the GUI components
sudokuPanel = new JPanel();
inputPanel = new JPanel();
buttonPanel = new JPanel();
sudokuTF = new JTextField[9][9];
gridPanel = new JPanel[9];
fileTF = new JTextField(10);
loadBtn = new JButton("Load Files");
hintsBtn = new JButton("Hints");
checkBtn = new JButton("Exact Check");
validBtn = new JButton("Check Valid");
// Add action listener to the buttons
loadBtn.addActionListener(this);
hintsBtn.addActionListener(this);
checkBtn.addActionListener(this);
validBtn.addActionListener(this);
// Add the file text field and load button to inputPanel
// (upper part of the frame)
inputPanel.setLayout(new FlowLayout());
inputPanel.add(fileTF);
inputPanel.add(loadBtn);
// Add the hints, check valid and check exact buttons to buttonPanel
// (lower part of the frame)
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(hintsBtn);
buttonPanel.add(validBtn);
buttonPanel.add(checkBtn);
// Set the center part into a 3x3 gird layout
sudokuPanel.setLayout(new GridLayout(3,3,5,5));
// inside each grid, we create panels with 3x3 grid layout
for(int i=0; i<9; i++) {
gridPanel[i] = new JPanel();
gridPanel[i].setLayout(new GridLayout(3,3));
sudokuPanel.add(gridPanel[i]);
}
// use a nested for loop to place all textfield into their place
// Each textfield represents a cell in a Sudoku
// and will take a Focus Listener
for(int i=0; i<9; i++)
for(int j=0; j<9; j++) {
sudokuTF[i][j] = new JTextField(2);
sudokuTF[i][j].setHorizontalAlignment(JTextField.CENTER);
sudokuTF[i][j].addFocusListener(this);
gridPanel[j/3+i/3*3].add(sudokuTF[i][j]);
}
// set lower, upper and the center panels into their place
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.add(sudokuPanel, BorderLayout.CENTER);
c.add(inputPanel, BorderLayout.NORTH);
c.add(buttonPanel, BorderLayout.SOUTH);
// Exit the system when the close button is clicked
setDefaultCloseOperation(EXIT_ON_CLOSE);
// pack the GUI to appropriate size
pack();
}
// Fill the text fields with the given Sudoku object
// All given cell will be disabled and colored with yellow background
public void fillFields(Sudoku s) {
for(int i=0; i<9; i++)
for(int j=0; j<9; j++) {
if(s.get(i,j)!=0) {
sudokuTF[i][j].setText(s.get(i,j)+"");
sudokuTF[i][j].setEnabled(false);
sudokuTF[i][j].setDisabledTextColor(Color.BLACK);
sudokuTF[i][j].setBackground(Color.YELLOW);
}
}
}
// Load the file into the three sudoku objects
// by calling the SudokuFile's readFile method
public void loadFiles(String filename) {
// You need to take the filename (e.g. s1.txt)
// and split it into the file and extension part
// sudoku will store the original file (same as filename)
//------------------------------------------------------------------------------------------------
sudoku =SudokuFile.readFile(filename);
/* FILL IN THE CALL HERE */;
// sudokuFilled will store the user filled sudoku data
// it will be the same as sudoku when it is initialized
/*** DON'T MODIFY ***/
sudokuFilled = (Sudoku)(sudoku.clone());
// sudokuSolution will store the solution file
// if filename = "s1.txt", the solution file will be "s1_ans.txt"
//------------------------------------------------------------------------------------------------
StringTokenizer ansname = new StringTokenizer(filename,".");
sudokuSolution = SudokuFile.readFile(ansname.nextToken() + "_ans." + ansname.nextToken());
/* FILL IN THE CALL HERE */;
// fill the text fields with the read-in sudoku
fillFields(sudoku);
}
// Check if all filled fields are exactly the same as the numbers in solution
public void exactMatch() {
for(int i=0; i<9; i++)
for (int j=0; j<9; j++) {
// sudokuFilled stores all given and filled numbers
// So, we will need to see if the number is given or filled
// before checking against sudokuSolution
// HINTS: If 0 is got from the original sudoku object,
// The number filled is not given
// If the number does not match with solution,
// change the background color to Color.Magenta
// HINTS: see code in fillFields method
// to see how to set the background color
if((sudokuFilled.get(i,j)!=0)&&(sudoku.get(i,j)==0))
if(sudoku.get(i,j) != sudokuSolution.get(i,j))
sudokuTF[i][j].setBackground(Color.MAGENTA);
}
}
// This method will check if the filled solution is logically valid
// by calling checkValid for each filled position in sudokuFilled.
public void checkValid() {
for(int i=0; i<9; i++)
for (int j=0; j<9; j++) {
//------------------------------------------------------------------------------------------------
if((sudokuFilled.get(i,j)!=0)&&(sudoku.get(i,j)==0))
if (sudokuFilled.checkValid(sudokuFilled.get(i,j),i,j) == false)
sudokuTF[i][j].setBackground(Color.MAGENTA);
// Similar to code in exactMatch
// But we are going to call checkValid for each of the filled position
}
}
// This method will show the hints in a message dialog
// You are going to give the hints for the coordinate (focusX, focusY)
// using hintsMessage method
public void hints() {
// Store the hints message in a string variable hints
String hints="";
//------------------------------------------------------------------------------------------------
hints = sudokuFilled.hintsMessage(focusX,focusY);
if(hints.equals(""))
//------------------------------------------------------------------------------------------------
JOptionPane.showMessageDialog(null,"There may be have wrong value","Error",JOptionPane.ERROR_MESSAGE);
// Show a message dialog telling user that
// there may be something wrong elsewhere
else
//------------------------------------------------------------------------------------------------
JOptionPane.showMessageDialog(null,"This is possible inr this blank ("+focusX+","+focusY+"):"+hints,"hints",JOptionPane.INFORMATION_MESSAGE);
// show a message dialog giving user the hints
// for the cell at (focusX, focusY)
}
// The actionPerformed method will be invoked when a button is clicked
// It will call the corresponding method to accomplish the task
/*** NO NEED TO MODIFY THE CODE IN THIS METHOD ***/
public void actionPerformed (ActionEvent e) {
if(e.getSource()==loadBtn) {
loadFiles(fileTF.getText());
} else if(e.getSource()==checkBtn) {
exactMatch();
} else if(e.getSource()==validBtn) {
checkValid();
} else if(e.getSource()==hintsBtn) {
hints();
}
}
// Record the focused cell by checking the event source
// exhaustively in a nested for loop
// store the current cell position to variables focusX, focusY
/*** THIS METHOD IS GIVEN AND COMPLETED ***/
/*** NO NEED TO MODIFY THE CODE IN THIS METHOD ***/
public void focusGained(FocusEvent e) {
for(int i=0; i<9; i++)
for (int j=0; j<9; j++)
if (sudokuTF[i][j]==e.getSource()) {
focusX = i;
focusY = j;
return;
}
}
// When a user leaves a text field,
// you need to put the number into filledSudoku object
// You need to do error checking before putting the number into filledSudoku
public void focusLost(FocusEvent e) {
JTextField temp = (JTextField)(e.getSource());
temp.setBackground(Color.WHITE);
// You should do some error checking here
//------------------------------------------------------------------------------------------------
int sTF = 0;
for(int i=0; i<9; i++){
for (int j=0; j<9; j++){
if (sudokuTF[i][j]==temp) { // search for the cell position
//------------------------------------------------------------------------------------------------
try{
sTF = Integer.parseInt(sudokuTF[i][j].getText());
}
catch(Exception s){
if(!((sudokuTF[i][j].getText()).equalsIgnoreCase("")))
JOptionPane.showMessageDialog(null,"You must input a number between 1 and 9.","Error",JOptionPane.ERROR_MESSAGE);
sudokuTF[i][j].setText("");
}
if ((sudokuTF[i][j].getText()).equalsIgnoreCase("")){
sudokuFilled.put(0,i,j);
}
else if ((sTF<1)||(sTF>9)){
if(!((sudokuTF[i][j].getText()).equalsIgnoreCase("")))
JOptionPane.showMessageDialog(null,"You must input a number between 1 and 9.","Error",JOptionPane.ERROR_MESSAGE);
sudokuTF[i][j].setText("");
}
else if((sTF>0)&&(sTF<10)){
sudokuFilled.put(sTF,i,j);
} // search for the cell position
// put 0 into the appropriate place in sudokuFilled
// if the text field is blank;
// put the digit into the appropriate place in sudokuFilled
// if the text filed is filled with a number
}
}
}
}
// main method starts your application
public static void main (String args[]) {
(new SudokuGUI()).setVisible(true);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -