This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

FocusEvent help......

 
Robert Upshall
Greenhorn
Posts: 25
  • 0
  • 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
  • 0
  • 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!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic