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
| public class DateTextFieldDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
JTextField textfield = new JTextField(10);
textfield.addActionListener(e-> System.out.println(getDateValue(textfield)));
setDateDocumentFilter(textfield);
panel.add(textfield);
frame.add(panel);
frame.setSize(600,400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void setDateDocumentFilter(JTextField textfield) {
((AbstractDocument)textfield.getDocument()).setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
throws BadLocationException {
string = normString(string);
fb.insertString(offset, string, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attrs)
throws BadLocationException {
string = normString(string);
fb.replace(offset, length, string, attrs);
}
private String normString(String string) {
return string.replaceAll("[^0-9/]", "");
}
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
fb.remove(offset, length);
}
});
}
/**
*
* @param field
* @param defaultValue
* @return
*/
public static LocalDate getDateValue(JTextField field) {
try {
return LocalDate.parse(field.getText(), DateTimeFormatter.ofPattern("dd/MM/yyyy"));
}
catch (DateTimeParseException e) {
return null;
}
}
} |
Partager