SAE21_2024/Sudoku/JTextFieldCharLimit.java

25 lines
792 B
Java
Raw Normal View History

2024-04-30 02:12:14 +02:00
import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
2024-04-30 11:18:29 +02:00
public class JTextFieldCharLimit extends PlainDocument
{
private int max;
JTextFieldCharLimit(int max) {
super();
this.max = max;
}
public void insertString(int offset, String text, AttributeSet attr) throws BadLocationException {
2024-04-30 19:33:40 +02:00
if (text == null){
2024-04-30 11:18:29 +02:00
return;
2024-04-30 19:33:40 +02:00
}
StringBuilder sb = new StringBuilder();
sb.append(getText(0, getLength()));
sb.insert(offset, text);
/* Vérifier si le texte ne contient que des chiffres de 1 à 9 et si il ne depasse pas 4 caractères */
if (sb.length() <= max && sb.toString().matches("[1-9]*")) {
2024-04-30 11:18:29 +02:00
super.insertString(offset, text, attr);
}
}
2024-04-30 02:12:14 +02:00
}