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
| public static void main(String[] args) throws ParseException {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField field = new JTextField();
field.setText("0");
((AbstractDocument)field.getDocument()).setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
throws BadLocationException {
string = string.replaceAll("\\D", ""); // on supprime tout ce qui n'est pas chiffre
super.insertString(fb, offset, string, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
text = text.replaceAll("\\D", ""); // on supprime tout ce qui n'est pas chiffre
if ( offset==0 && length==field.getText().length() && text.length()==0 ) { // si on remplace le contenu complet du champ par unue chaîne vide
text = "0"; // on remet un 0 dans le champ
}
super.replace(fb, offset, length, text, attrs);
}
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
if ( offset==0 && length==field.getText().length() ) { // si on supprime tous les caractères
super.replace(fb, 0, field.getText().length(), "0", null); // on remet un 0 dans le champ
}
else {
super.remove(fb, offset, length);
}
}
});
field.addActionListener(e->JOptionPane.showMessageDialog(frame, "Saisie : "+field.getText()));
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets=new Insets(3,3,3,3);
panel.add(new JLabel("Saisie :"), gbc);
gbc.weightx=1;
gbc.fill=GridBagConstraints.HORIZONTAL;
panel.add(field, gbc);
gbc.gridy=1;
gbc.weightx=0;
gbc.gridwidth=2;
gbc.anchor=GridBagConstraints.CENTER;
gbc.fill=GridBagConstraints.NONE;
JButton button = new JButton("Valider");
panel.add(button, gbc);
button.addActionListener(e-> JOptionPane.showMessageDialog(frame, "Saisie : "+field.getText()));
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} |
Partager