package [Link].
swing;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
* NumericTextField allows only numbers in the text field and not even decimal
* points. Also, it restricts the length of input.
* @author mrityunjoy_saha
* @version 1.0
* @since Apex 1.2
*/
public class NumericTextField {
/**
*
*/
public void createUI() {
final JFrame frame = new JFrame("NumericTextField");
[Link](400, 400);
JPanel panel = new JPanel();
JLabel label=new JLabel("Enter some data (only numbers would be allowed):");
final JTextField textField = new JTextField(30);
// Add the document filter to text field for nemric and length check.
((AbstractDocument) [Link]()).setDocumentFilter(new
NumericAndLengthFilter(
5));
[Link](label);
[Link](textField);
[Link]().add(panel);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
/**
* Entry point of the application.
* @param args Input arguments.
*/
public static void main(String[] args) {
final NumericTextField test = new NumericTextField();
[Link](new Runnable() {
public void run() {
[Link]();
}
});
}
/**
* A document filter for numeric and length check.
*/
private class NumericAndLengthFilter extends DocumentFilter {
/**
* Number of characters allowed.
*/
private int length = 0;
/**
* Restricts the number of charcacters can be entered by given length.
* @param length Number of characters allowed.
*/
public NumericAndLengthFilter(int length) {
[Link] = length;
}
@Override
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws
BadLocationException {
if (isNumeric(string)) {
if ([Link] > 0 && [Link]().getLength() + string.
length()
> [Link]) {
return;
}
[Link](fb, offset, string, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws
BadLocationException {
if (isNumeric(text)) {
if ([Link] > 0 && [Link]().getLength() + text.
length()
> [Link]) {
return;
}
[Link](fb, offset, text, attrs);
}
}
/**
* This method tests whether given text can be represented as number.
* This method can be enhanced further for specific needs.
* @param text Input text.
* @return {@code true} if given string can be converted to number; otherwise
returns {@code false}.
*/
private boolean isNumeric(String text) {
if (text == null || [Link]().equals("")) {
return false;
}
for (int iCount = 0; iCount < [Link](); iCount++) {
if ()) {
return false;
}
}
return true;
}
}
}