-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJDigitField.java
91 lines (76 loc) · 2.62 KB
/
JDigitField.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
/**
* Object that extends JTextField to show error if the content is not valid
* for a sudoku cell
*/
public class JDigitField extends JTextField
implements ActionListener, FocusListener {
/** Please warnings... */
private static final long serialVersionUID = 1L;
/** The color used in correct cells */
private static final Color normalColor = Color.WHITE;
/** The color used in clashing cells */
private static final Color clashingColor = new Color(233, 47, 47);
/** When focus gained, stores the old text */
private String oldText;
/** The sudoku gui this JDigitField is in */
private SudokuGUI gui;
/** The coordinate of this digit in the grid */
private int i, j;
/**
* Constructor...
* @param sgui The sudoku gui this JDigitField is in
* @param i_ The row index of this digit in the grid
* @param j_ The column index of this digit in the grid
*/
public JDigitField(SudokuGUI sgui, int i_, int j_) {
super();
addActionListener(this);
addFocusListener(this);
addKeyListener(sgui);
gui = sgui;
i = i_;
j = j_;
setBackground(normalColor);
}
@Override
public void actionPerformed(ActionEvent e) {
JDigitField source = (JDigitField) e.getSource();
String t = source.getText();
if (!t.isEmpty() && !t.matches("^\\d$")) {
JOptionPane.showMessageDialog(null, "Invalid digit '" + t + "'",
"Warning", JOptionPane.WARNING_MESSAGE);
setText(oldText);
return;
}
try {
gui.signalChange(i, j, Integer.parseInt(t), true);
setBackground(normalColor);
} catch (NumberFormatException ex1) {}
// no NumberFormatException should be caught because of regex
catch (CannotAcceptException ex2) {
setBackground(clashingColor);
}
}
@Override
public void focusGained(FocusEvent e) {
oldText = getText();
gui.focusUpdate(i, j);
}
@Override
public void focusLost(FocusEvent e) {
String t = getText();
if (!oldText.equals(t))
actionPerformed(new ActionEvent(this, 0, ""));
}
/** @return Wether or not this cell is clashing */
public boolean isClashing() {
return !getBackground().equals(normalColor);
}
}