Can we extend JTextField with Listeners

Hello,

I am new to Java, I was trying to JTextField and implementing listeners also to make a new class so as to make make it more user friendly.

The code I had written is given below.

Though the TextField is working as it should, the validations are not taking place.

Please mail me a copy of the answer at guptaabrasives@vsnl.com

The code is :

//File Name is: ATextField.java// ATextField.java

import java.awt.event.*;

import javax.swing.*;

public class ATextField extends JTextField implements KeyListener, FocusListener

{

//int fieldLength = this.getText().length();

char fType;

boolean validEntry = true;

String tTip;

public ATextField(int fLength, String toolTip, char FieldType)

{

super(fLength);

this.setToolTipText("Enter "+toolTip+" here");

fType= FieldType;

tTip=toolTip;

addFocusListener(this);

addKeyListener(this);

}

public void keyTyped(KeyEvent e)

{

JTextField thisField = (JTextField)e.getSource();

boolean aError = false ;

char c = e.getKeyChar();

int keyCode = e.getKeyCode();

if ((fType == 'N' || fType == 'n') && (keyCode <48 || keyCode > 57))

{

//beep();

e.setKeyCode(0);

}

if ((fType == 'D' || fType == 'd') && ((thisField.getText().length()==3 || thisField.getText().length() == 6) && (c != '/' || c!='-' || c != '.')))

{

e.setKeyCode(0);

}

else if ((fType == 'D' || fType == 'd') && (keyCode <48 || keyCode > 57))

{

//beep();

e.setKeyCode(0);

}

}

public void keyPressed(KeyEvent e)

{

}

public void keyReleased(KeyEvent e)

{

}

public void focusGained(FocusEvent e)

{

}

public void focusLost(FocusEvent e)

{

}

public boolean chkNullEntry()

{

String s1 = this.getText();

boolean aError = false;

if (s1.length() ==0)

{

return true ;

}

else

return false;

}

public boolean valid()

{

return validEntry;

}

}

[2251 byte] By [NeerajGupta] at [2007-9-26 8:16:36]
# 1
If your trying to prevent characters from being typed then use e.consume() to prevent the event from travelling up the chain to the JTextField rather than setting the key code to 0.Ronny.
ronnybatty at 2007-7-1 18:46:52 > top of Java-index,Archived Forums,New To Java Technology Archive...
# 2

If you are using a swing JTextComponent, like JTextField, a better approach is to change the Document. There's an answer here that might be adaptable for what you need.

http://forums.java.sun.com/thread.jsp?forum=54&thread=107812

Basically, you extend the Document class and override the insertString() method. It's easy and works.

atmguy at 2007-7-1 18:46:52 > top of Java-index,Archived Forums,New To Java Technology Archive...