javasweeper/CustomTextField.java

71 lines
1.6 KiB
Java
Raw Normal View History

2023-05-24 17:34:20 -07:00
import java.awt.event.*;
import javax.swing.*;
public class CustomTextField extends JTextField {
private static final int COLS = 4;
private final int MIN_VALUE;
private final int MAX_VALUE;
public CustomTextField(int defaultValue, int minValue, int maxValue) {
super(Integer.toString(defaultValue), COLS);
MIN_VALUE = minValue;
MAX_VALUE = maxValue;
addFocusListener(new FocusAdapter() {
// Auto select when focused
@Override
public void focusGained(FocusEvent e) {
selectAll();
}
// Auto format input when unfocused
@Override
public void focusLost(FocusEvent e) {
formatText();
}
});
}
protected void formatText() {
String text = getText();
// If tried to input a negative number, set it to the minimum
if (text.isEmpty() || text.charAt(0) == '-') {
setValue(getMinValue());
return;
}
// Remove all the nondigit characters and all leading zeros
String filteredText = text.replaceAll("(^[^1-9]+|\\D)", "");
if (filteredText.isEmpty()) {
setValue(getMinValue());
return;
}
// To prevent integer overflow when parsing, just set it to max
// when it's more than 4 digits
if (filteredText.length() > 4) {
setValue(getMaxValue());
return;
}
// Now that we finally have the intended int, clamp and set it
setValue(Difficulty.clampInt(Integer.parseInt(filteredText), getMinValue(), getMaxValue()));
}
// Use protected getters and setters so we can override them if necessary
protected int getMinValue() {
return MIN_VALUE;
}
protected int getMaxValue() {
return MAX_VALUE;
}
private void setValue(int value) {
setText(Integer.toString(value));
}
}