Focus issue

From: Hegemony Cricket (schnitzi_at_gmail.com)
Date: 10/28/04


Date: 27 Oct 2004 16:45:38 -0700

Here's a stumper for you... I've boiled down the problem to a
simplified sample program below.

What I want basically is a confirm step that occurs when focus
switches between two screen components.

The below program looks like it should work. The Ok option
works fine, actually, but if you hit Cancel instead of Ok on
the popup, the popup appears twice, for reasons I can't discern.

Any ideas?

AdTHANKSvance,
Mark

----
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class focusTest extends JFrame
{
    public focusTest()
    {
        JTextField tf = new JTextField(20);
        tf.addFocusListener( new FocusAdapter()
            {
            	public void focusLost( FocusEvent fe )
            	{
            	    if ( ! fe.isTemporary() )
            	    {
	            	    int result = JOptionPane.showConfirmDialog(
focusTest.this, "Are you sure?", "Please confirm",
JOptionPane.OK_CANCEL_OPTION );
	            	    if ( result == JOptionPane.OK_OPTION )
	            	    {
	            	        fe.getOppositeComponent().requestFocus();
	            	    }
	            	    else	// CANCEL_OPTION
	            	    {
	            	        fe.getComponent().requestFocus();
	            	    }
            	    }
            	}
            } );
        JTextField tf2 = new JTextField(20);
        getContentPane().setLayout( new FlowLayout() );
        getContentPane().add( tf );
        getContentPane().add( tf2 );
        
        setSize( new Dimension( 500, 100 ) );
        
        this.addWindowListener(new WindowAdapter()
            {
                public void windowClosing(WindowEvent evt)
                {
                    setVisible( false );
                    focusTest.this.dispose();
                }
            });
    }
    
    public static void main( String[] args )
    {
        focusTest ft = new focusTest();
        ft.setVisible( true );
    }
}