Solution 1
Simple but It can't work for "CTRL + V" scenario
private class NumberOnlyAdapter extends KeyAdapter { private final int maxLength; private NumberOnlyAdapter(int maxLength) { this.maxLength = maxLength; } @Override public void keyTyped(KeyEvent e) { char typed = e.getKeyChar(); CharMatcher notDigit = noneOf("0123456789").and(isNot((char) VK_BACK_SPACE)).and(isNot((char) VK_DELETE)); JTextField textField = (JTextField) e.getComponent(); if (notDigit.apply(typed) || textField.getText().length() >= maxLength) { e.consume(); } } } ... int maxLength = 8; JTextField textField = new JTextField(); textField.addKeyListener(new NumberOnlyAdapter(maxLength));
It's work for all conditions
import static org.apache.commons.lang3.StringUtils.*; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; public class NumericOnlyAndMaxLengthFilter extends DocumentFilter { private int maxLength = 0; public NumericOnlyAndMaxLengthFilter() { // allow any length of numeric } public NumericOnlyAndMaxLengthFilter(int maxLength) { this.maxLength = maxLength; } @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { if (isNumeric(string)) { if (isExceedMaxLength(fb, string)) { return; } super.insertString(fb, offset, string, attr); } } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { if (isNumeric(text)) { if (isExceedMaxLength(fb, text)) { return; } super.insertString(fb, offset, text, attrs); } } private boolean isExceedMaxLength(FilterBypass fb, String text) { return maxLength > 0 && (fb.getDocument().getLength() + text.length()) > maxLength; } } ... int maxLength = 8; JTextField textField = new JTextField(); ((AbstractDocument)textField .getDocument()).setDocumentFilter(new NumericOnlyAndMaxLengthFilter(maxLength));
This comment has been removed by the author.
ReplyDeletegreat stuff admin
ReplyDeletethis also informative check here : www.kodingexamples.blogspot.com/2014/04/how-to-make-jtextfield-accept-only.html