Tuesday, March 11, 2008

NumberFormattedTextField will allow user to enter only Number

This class used for Number Format validation.

/**
* TextUtils.java method which will used to validate the Text..For Double.
* public static boolean isDouble(String p_value)
* {
* double d = 0;
* try
* {
* d = Double.parseDouble(p_value);
* }
* catch (NumberFormatException e)
* {
* System.out.print("Error in isdouble :: ");
* e.printStackTrace();
* return false;
* }
* return true;
* }
*
* This will allow also limited character added by client. using setMaxLimit() method
*/
package com.joshi.resource;

import com.jdt.smartclient.utils.TextUtils;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;

/**
*
* @author Shirin
*/
public class NumberFormattedTextField extends JTextField {

boolean isNegativeAllowed = true;
int maxLimit=0;
boolean isMaxLimit=false;

public NumberFormattedTextField(boolean p_isNegativeAllowed) {
this();
isNegativeAllowed = p_isNegativeAllowed;
}

public NumberFormattedTextField() {
super();
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
keyTypedManage(e);
}
});
}

public void setMaxLimit(int maxLimit) {
if(maxLimit>0) {
this.maxLimit = maxLimit;
isMaxLimit=true;
} else {
isMaxLimit=false;
}
}

public int getMaxLimit() {
return maxLimit;
}


public void setNegativeAllowed(boolean p_isNegativeAllowed) {
isNegativeAllowed = p_isNegativeAllowed;
}
public boolean getNegativeAllowed() {
return isNegativeAllowed;
}


private void keyTypedManage(KeyEvent e) {
JTextField input = (JTextField) e.getSource();

System.out.println(" Caret Position " + input.getCaretPosition());
System.out.println("Code : " + e.getKeyCode());
System.out.println("Char :" + e.getKeyChar());
String inputText = input.getText();
String tempConcat="";

if(e.getKeyChar()==' ') {
e.consume();
return;
}

if (input.getCaretPosition() == 0 && isNegativeAllowed) {
if (inputText.trim().length() == 0) {
if (e.getKeyChar() == '-') {
// Checking for MaxLimit
if(isMaxLimit && inputText.length()>=getMaxLimit()) {
e.consume();
}
return;
} else {
tempConcat = inputText + e.getKeyChar();
if (!TextUtils.isDouble(tempConcat)) {
e.consume();
}
}
} else {
tempConcat = e.getKeyChar() + inputText;
System.out.println("T1 " + tempConcat);
if (!TextUtils.isDouble(tempConcat)) {
System.out.println("T1 Not Valid");
e.consume();
return;
}
}
} else {
tempConcat = inputText + e.getKeyChar();
System.out.println("InputText >> " + tempConcat);
if (!TextUtils.isDouble(tempConcat)) {
System.out.println("Not Valid");
e.consume();
} else {
if (e.getKeyChar() == 'd' || e.getKeyChar() == 'D' || e.getKeyChar() == 'f' || e.getKeyChar() == 'F') {
System.out.println("Valid");
e.consume();
} else {
if(isMaxLimit && inputText.length()>=getMaxLimit()) {
e.consume();
}
}

}
}


}
}



No comments:

Contributors