File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes FocusEvent help...... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "FocusEvent help......" Watch "FocusEvent help......" New topic

FocusEvent help......

Robert Upshall

Joined: Aug 23, 2001
Posts: 25
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)
catch (NumberFormatException nfe)
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?
Renee Zhang
Ranch Hand

Joined: Sep 10, 2001
Posts: 72
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!
I agree. Here's the link:
subject: FocusEvent help......
It's not a secret anymore!