EarthWeb
Developer.com
Site
windows 2000
visual c++
java
visual basic
javascripts
recommend it
 
Book
thinking in java
 
Interact
forum
guest book
jobs
jokes
what's new

share code
 
Resource
add resource
modify resource
new resource
 

[Internet Jobs]
-----
Java by E-mail:

Get the weekly e-mail highlights on Java!
-----

-

Validate a value on the lostFocus event


Author: Real Gagnon
Author's WebSite: http://tactika.com/realhome/realhome.html

The problem is when the lostFocus occurs on a Component, the gainedFocus is already sent for the next component in the SystemEventQueue. We must grab this event, and request the focus for the previous component (if there is a validation error). We can't use Toolkit.getDefaultToolkit().getSystemEventQueue() directly to remove the gainedFocus event because of security restriction in Applet. This can be done with invokeLater method of the SwingUtilities class.


  import java.awt.*; 
  import java.awt.event.*;
  import com.sun.java.swing.*;
  //import javax.swing.*;

  public class tswing extends JApplet {
    JTextField textfield1, textfield2;
    JLabel label1;

    public void init() {
      getContentPane().setLayout(new FlowLayout());
      //
      label1 = new JLabel("must be 'a' or 'b' ");
      textfield1 = new JTextField(5);
      getContentPane().add(label1);
      getContentPane().add(textfield1);
      textfield2 = new JTextField(5);
      getContentPane().add(textfield2);

      textfield1.addFocusListener(new FocusListener() {
         public void focusGained(FocusEvent e) {}; // not needed

         public void focusLost(FocusEvent e) {
           if (!e.isTemporary() && isEnabled() ) {
             String fieldContent = textfield1.getText();
             if (!fieldContent.equals("a") && !fieldContent.equals("b")) {
               Toolkit.getDefaultToolkit().beep();
               System.out.println("illegal value! " + fieldContent );
               SwingUtilities.invokeLater(new FocusGrabber(textfield1));         
               }
           }}
         });
      }
  }



Usage


 import com.sun.java.swing.*;
 //import javax.swing.*;

 public class FocusGrabber implements Runnable {
   private JComponent component;
  
   public FocusGrabber(JComponent component) {
    this.component = component;
    }
   public void run() {
    component.grabFocus();
    }
 }



Posted On: 5-Jul-1999

internet.commerce



Acceptable Use Policy


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers