Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import javax.swing.text.*;
- /**
- * Force a jTextField to accept only integer value.
- * In order to invoke this to a jTextField,
- * you must customize your jTextField's code, from default-code to custom-creation.
- * Then change the creation of jTextField's instance to the instance of this class (IntegerField).
- *
- * @author Erieze Lagera
- */
- public class IntegerField extends JTextField {
- private int limit;
- private String field_name;
- /**
- * Create a simple instance of IntegerField.
- * @param name Name of jTextField who created this instance
- */
- public IntegerField(String name) {
- super();
- setFieldName(name);
- }
- /**
- * Create an instance with column length limitation.
- * This will limit user input length based on your set limit.
- * @param name Name of jTextField who created this instance
- * @param limit Preferred column length
- */
- public IntegerField(String name, int limit) {
- super(limit);
- setLimit(limit);
- setFieldName(name);
- if (limit <= 0) {
- System.out.println("[WARNING] Bad limit value from field " + getFieldName() + ", no limitation will be implemented...");
- }
- }
- @Override
- protected Document createDefaultModel() {
- return new UpperCaseDocument();
- }
- /**
- * Overrides the document of your jTextField, to perform the hack.
- */
- private class UpperCaseDocument extends PlainDocument {
- @Override
- public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
- if (str == null) {
- return;
- }
- char[] charArr = str.toCharArray();
- boolean ok = true;
- for (int i = 0; i < charArr.length; i++) {
- try {
- Integer.parseInt(String.valueOf(charArr[i]));
- } catch (NumberFormatException e) {
- ok = false;
- break;
- }
- }
- if (ok) {
- if (limit > 0) {
- if (offset < limit) {
- super.insertString(offset, new String(charArr), a);
- }
- }
- else {
- super.insertString(offset, new String(charArr), a);
- }
- }
- }
- }
- /**
- * Get the current value for limit.
- * @return The value of <i> limit </i>.
- */
- public int getLimit() {
- return limit;
- }
- /**
- * Set the input limit for your jTextField.
- * @param newValue Limit value
- */
- private void setLimit(int newValue) {
- this.limit = newValue;
- }
- /**
- * Get the jTextField name who create this instance.
- * @return Name of your jTextField
- */
- public final String getFieldName() {
- return field_name;
- }
- /**
- * Set the name of jTextField who create this instance.
- * @param field_name Name of your jTextField
- */
- public void setFieldName(String field_name) {
- this.field_name = field_name;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment