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
| public class DemoDocumentListener {
public static void main(String[] args) {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
frame.add(panel);
panel.add(new JLabel("Nom :"), new GridBagConstraints(0,0,1,1,0,0,GridBagConstraints.BASELINE,GridBagConstraints.NONE,new Insets(0, 0, 0, 0),0,0));
JTextField inputField=new JTextField();
panel.add(inputField, new GridBagConstraints(1,0,1,1,1,0,GridBagConstraints.BASELINE,GridBagConstraints.HORIZONTAL,new Insets(0, 5, 0, 0),0,0));
inputField.setVerifyInputWhenFocusTarget(false);
final Border inputFieldBorder = inputField.getBorder();
final Border inputFieldErrorBorder = BorderFactory.createLineBorder(Color.RED);
inputField.setBorder(inputFieldErrorBorder);
inputField.setInputVerifier(new InputVerifier() {
@Override
public boolean verify(JComponent input) {
String text=((JTextField)input).getText();
boolean ok = text.length()>3 && text.length()<25;
if ( !ok ) {
input.setBorder(inputFieldErrorBorder);
}
else {
input.setBorder(inputFieldBorder);
}
return ok;
}
});
((AbstractDocument)inputField.getDocument()).setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr)
throws BadLocationException {
check(offset, 0, text);
super.insertString(fb, offset, text, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
check(offset, length, text);
super.replace(fb, offset, length, text, attrs);
}
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
check(offset, length, "");
super.remove(fb, offset, length);
}
private void check(int offset, int length, String text) {
String currentText = inputField.getText();
int newLength = currentText.length()-length+text.length();
if ( newLength>3 && newLength<25 ) {
inputField.setBorder(inputFieldBorder);
}
else {
inputField.setBorder(inputFieldErrorBorder);
}
}
});
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
buttonPanel.add(new JButton("OK"));
frame.add(buttonPanel,BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
} |
Partager