bijoyn
asked on
JTextField Difficulty
I need to do following things on a JTextField
1. Make sure only numbers are entered. Meaning that when a user presses a character on the keyboard nothing happens on the JTextField
2. Limit the entry to 4 digits.
3. Not allow -ve values
4. Once a valid value is entered, then on the enter key do something.
Please help me with this. Since I have tried all possible things in my capacity to figure out how to accomplish this.
Thanks In Advance
Bijoy
1. Make sure only numbers are entered. Meaning that when a user presses a character on the keyboard nothing happens on the JTextField
2. Limit the entry to 4 digits.
3. Not allow -ve values
4. Once a valid value is entered, then on the enter key do something.
Please help me with this. Since I have tried all possible things in my capacity to figure out how to accomplish this.
Thanks In Advance
Bijoy
Hi again,
Here is the code to limit the no. of characters.
-------------------------- -------
import com.sun.java.swing.text.*;
public class LimitedPlainDocument extends DFPlainDocument
{
public LimitedPlainDocument (int maxLength)
{
this.maxLength = maxLength;
}
private int maxLength;
public final int getMaxLength()
{
return maxLength;
}
public final void setMaxLength (int maxLength)
{
this.maxLength = maxLength;
}
public void insertString (int offs, String str, AttributeSet a)
throws
BadLocationException
{
if (str == null || getLength() + str.length() <= maxLength)
super.insertString (offs, str, a);
else
{
int remainder = maxLength - getLength();
if (remainder > 0)
super.insertString (offs, str.substring (0,
remainder), a);
}
}
}
call jTextField.setDocument(new LimitedPlainDocument(5));
and u won't be able to enter more than 5 chars even using Clipboard operations.
:-)
bye
Mohan
Here is the code to limit the no. of characters.
--------------------------
import com.sun.java.swing.text.*;
public class LimitedPlainDocument extends DFPlainDocument
{
public LimitedPlainDocument (int maxLength)
{
this.maxLength = maxLength;
}
private int maxLength;
public final int getMaxLength()
{
return maxLength;
}
public final void setMaxLength (int maxLength)
{
this.maxLength = maxLength;
}
public void insertString (int offs, String str, AttributeSet a)
throws
BadLocationException
{
if (str == null || getLength() + str.length() <= maxLength)
super.insertString (offs, str, a);
else
{
int remainder = maxLength - getLength();
if (remainder > 0)
super.insertString (offs, str.substring (0,
remainder), a);
}
}
}
call jTextField.setDocument(new
and u won't be able to enter more than 5 chars even using Clipboard operations.
:-)
bye
Mohan
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
here's my simplified solution:
class DocumentListenerExample extends JPanel implements DocumentListener, KeyListener {
JTextField Field = null;
public class DocumentListenerExample() {
Field = new JTextField();
getContainer().add(Field);
Field.getDocument().addDoc uementList ener(this) ;
Field.addKeyListener(this) ;
}
public void changeUpdate(DocumentEvent evt) { }
public void insertUpdate(DocumentEvent evt) {
removeUpdate(evt);
}
public void removeUpdate(DocumentEvent evt) {
String error = validate(Field.getText());
if (error != null) {
//System.out.println("Erro r: " + error);
// show dialog or something...
}
}
protected String validate(String text) {
int num = -1;
try {
num = Integer.parseInt(text);
}
catch (NumberFormatException e) {
return e.getText();
}
if (num < 0) return "Number cannot be negative.";
return null;
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {
if ((int) e.getKeyChar() == KeyEvent.VK_ENTER) {
//DO SOMETHING...
}
}
public static final void main(String args[]) {
JFrame f = new JFrame();
f.getContainer().add(new DocumentListenerExample()) ;
f.pack();
f.show()
}
}
I didnt compile this program but should do the trick...
Hope it helps,
Rob
class DocumentListenerExample extends JPanel implements DocumentListener, KeyListener {
JTextField Field = null;
public class DocumentListenerExample() {
Field = new JTextField();
getContainer().add(Field);
Field.getDocument().addDoc
Field.addKeyListener(this)
}
public void changeUpdate(DocumentEvent
public void insertUpdate(DocumentEvent
removeUpdate(evt);
}
public void removeUpdate(DocumentEvent
String error = validate(Field.getText());
if (error != null) {
//System.out.println("Erro
// show dialog or something...
}
}
protected String validate(String text) {
int num = -1;
try {
num = Integer.parseInt(text);
}
catch (NumberFormatException e) {
return e.getText();
}
if (num < 0) return "Number cannot be negative.";
return null;
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {
if ((int) e.getKeyChar() == KeyEvent.VK_ENTER) {
//DO SOMETHING...
}
}
public static final void main(String args[]) {
JFrame f = new JFrame();
f.getContainer().add(new DocumentListenerExample())
f.pack();
f.show()
}
}
I didnt compile this program but should do the trick...
Hope it helps,
Rob
ASKER
Hi Mohan & Rob
Thanks for the solutions. The difference between the two solutions are many. As I had specified. I wanted to restrict the user to input only 4 characters ( which Mohan gave me a solution ). The second was to input only numeric
values to the same textfield. this though Mohan has given me the solution. I am not sure how to combine the 1st and the second requirement together because u can setDocument to one class at a time. Also Mohan once u set the textfield to be numeric, u need not write the code for -ve numbers or do we ?.
Rob your solution allows me to enter non-numeric which is validated later. This is not what I wanted.
Mohan can u tell me how to combine the NUMERIC and the MAXLENGTH together in one Document class
Appreciate it.
Bijoy
Thanks for the solutions. The difference between the two solutions are many. As I had specified. I wanted to restrict the user to input only 4 characters ( which Mohan gave me a solution ). The second was to input only numeric
values to the same textfield. this though Mohan has given me the solution. I am not sure how to combine the 1st and the second requirement together because u can setDocument to one class at a time. Also Mohan once u set the textfield to be numeric, u need not write the code for -ve numbers or do we ?.
Rob your solution allows me to enter non-numeric which is validated later. This is not what I wanted.
Mohan can u tell me how to combine the NUMERIC and the MAXLENGTH together in one Document class
Appreciate it.
Bijoy
ASKER
Mohan,
I could combine the two functionalities within the same class and thanks a lot for your help.
Bijoy.
I could combine the two functionalities within the same class and thanks a lot for your help.
Bijoy.
He is the code I am using to enter only numbers
Put a filtering document in you JTextField is best.
Here is the class that I use to filter out thing basis on the
mask string.
In you application, You only need to do:
JTextField jtf = new JTextField(();
//
// Only allow numeric 0,1,2,3,4,5,6,7,8,9 to be entered
//
jtf.setDocument(new MyTextFilter(MyTextFilter.
Let me know if you need further help. Have fun!
//
// file MyTextFilter.java
//
import com.sun.java.swing.text.At
import com.sun.java.swing.text.Ba
import com.sun.java.swing.text.Pl
public class MyTextFilter
extends PlainDocument
{
public static final String LALPHA =
"abcdefghijklmnopqrstuvwxy
public static final String UALPHA =
"ABCDEFGHIJKLMNOPQRSTUVWXY
public static final String ALPHA = LALPHA + UALPHA;
public static final String NUMERIC = "0123456789";
public static final String ALPHA_NUMERIC = ALPHA + NUMERIC;
public MyTextFilter()
{
this(ALPHA_NUMERIC);
}
public MyTextFilter(String p_charset)
{
m_charset = p_charset;
}
public void insertString(int p_offset,
String p_str,
AttributeSet p_attr)
throws BadLocationException
{
if (p_str == null)
return;
for (int i=0; i<p_str.length(); i++)
if (m_charset.indexOf(p_str.v
return;
super.insertString(p_offse
}
/**
* the allow input character set
*/
protected String m_charset = null;
}
:-)
bye
Mohan