• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

FocusEvent help......

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic