• Post Reply Bookmark Topic Watch Topic
  • New Topic

FocusListener  RSS feed

 
Shannon Sims
Ranch Hand
Posts: 197
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
Does a FocusListener only work if the user clicks within a JTextField? I need the JTextField to catch a mouse click or a user tabbing into the field. During my testing, it appears its only catching the click and not a tab. Should I use another listener or use a different listener?

I'm trying to avoid a user entering more than 3 numeric characters into the JTextField. Right now, my JTextField has two listeners, a KeyListener ( to ensure only 3 numeric values are entered, then push focus to the next component ) and a FocusListener ( removes all values already entered, to allow reentry ).

Thanks in advance for everyone's help!
 
Mohan Ramamoorthy
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shannon,
Hope this code will solve ur requirement.Here the createDefaultModel() method is overridden with our requirement.
So now the keylistener is not necessary for this implementation even focus listener also.
We can use normal requestFocus() method to change the focus.

During the TextField initialization add these code


JTextField myTextField = new JTextField();
myTextField.setDocument(createDefaultModel());
..............

and add these two methods..

protected javax.swing.text.Document createDefaultModel()
{
return new javax.swing.text.PlainDocument() {
public void insertString(int offset, String value,
javax.swing.text.AttributeSet as)
{
if (isValid(offset, value, as))
{
try
{
super.insertString(offset, value, as);
}
catch (javax.swing.text.BadLocationException e)
{
System.out.println("Exception in insertString() of FolderField : " + e);
}
}
}
};
}


private boolean isValid(int offset, String value, javax.swing.text.AttributeSet as)
{
//check the valid characters
if (offset < 3)
{
for (int i = 0; i < value.length(); i++)
{
if (i > 3 ||Character.isDigit(value.charAt(i)) == false)
{
java.awt.Toolkit.getDefaultToolkit().beep();
return false;
}
}
return true;
}
return false;
}
 
Shannon Sims
Ranch Hand
Posts: 197
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mohan,
Thanks for your reply, I was beginning to think there was no solution to my problem. The code sample you provided looks great!!! Since I'm fairly new to Swing, I would have never dreamed of this solution.

Thanks again!!!
 
Mohan Ramamoorthy
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome shannon

Regards
Mohan
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!