Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

FocusEvent help......

 
Robert Upshall
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have class that extends FocusAdapter, i have ovenriden the focusLost method to be the following:
public void focusLost(FocusEvent e)
{
JTextField textField = (JTextField) e.getSource();
String content = textField.getText();
if (content.length() != 0)
{
try
{
Float.parseFloat(content);
}
catch (NumberFormatException nfe)
{
Toolkit.getDefaultToolkit().beep();
textField.requestFocus();
textField.selectAll();
}
}
}
As the catch block shows i want to beep, set focus back to the field that had the error and select the text.
My problem is focus will not return to the field, it does the beep and it selects the text but focus does not return, what am I doing wrong?
Is they another way I can do the valadiation?
Robert
 
Renee Zhang
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Robert:
Do you want to try another way to do it?
I have a class in my project call IntegerDocument. Just set yourTextField.setDocument(new IntegerDocument(anynumber); It will also limit the digit number user enters.
import javax.swing.*;
import javax.swing.text.*;
public class IntegerDocument extends PlainDocument {
int maxDigitsNumber;
public IntegerDocument (int maxDigitsNumber) {
super ();
this.maxDigitsNumber = maxDigitsNumber;
}
public void insertString (int offset, String s, AttributeSet attributeSet)
throws BadLocationException {
try {
int number = Integer.parseInt(s);
if (offset < this.maxDigitsNumber) {
s = (new Integer(number)).toString();
super.insertString(offset, s, attributeSet);
} else {
JOptionPane.showMessageDialog(null, this.maxDigitsNumber + " digits only!");
}
} catch (Exception e) {
// JOptionPane.showMessageDialog(null, "Integer Only!");
//Or do the beep.
}
}
}
Good luck!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic