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 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);
     textfield2 = new JTextField(5);

     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")) {
              System.out.println("illegal value! " + fieldContent );
              SwingUtilities.invokeLater(new FocusGrabber(textfield1));         

import javax.swing.*;

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

JDK1.3 provides a new class, InputVerfier, which can be used to do that.

  import java.awt.*;
 import java.util.*;
 import java.awt.event.*;
 import javax.swing.*;

 // the first JTextField expects the string "howto" as input, 
 // and will allow focus to change only if the required string
 // is typed.

 class VerifierTest extends JFrame {
  public VerifierTest () {
    JTextField tf,tf2;
    tf = new JTextField ("howto is required");

    getContentPane().add (tf, BorderLayout.NORTH);
    tf.setInputVerifier(new HowtoVerifier());

    tf2 = new JTextField ("howto come here");
    getContentPane().add (tf2, BorderLayout.SOUTH);

    addWindowListener(new WindowCloser());

 public static void main (String [] args) {
   Frame f = new VerifierTest ();

class WindowCloser extends WindowAdapter {
 public void windowClosing(WindowEvent e) {
   Window win = e.getWindow();

class HowtoVerifier extends InputVerifier {
  public boolean verify(JComponent input) {
    JTextField tf = (JTextField) input;
    String pass = tf.getText();
    return pass.equals("howto");