/* TestPrompt */ import java.applet.*; import java.awt.*; import java.util.*; import java.awt.event.*; public class TestPrompt extends Applet implements ActionListener, TextListener { TextField tf1; Panel crashPanel, crashPanel1, crashPanel2; Button crashButton, dontCrashButton; boolean isCrash = false; String tf1Prompt = "The prompt"; public void init( ) { setLayout( new BorderLayout( ) ); setSize( 250, 150 ); tf1 = new TextField( tf1Prompt ); add( tf1, BorderLayout.NORTH ); tf1.addTextListener( this ); crashPanel = new Panel(); crashPanel.setLayout( new GridLayout( 0, 1 ) ); crashButton = new Button( "Do a setCaretPosition() " ); crashButton.addActionListener( this ); crashPanel1 = new Panel(); crashPanel1.add( crashButton ); dontCrashButton = new Button( "Don't do a setCaretPosition() - active" ); dontCrashButton.addActionListener( this ); crashPanel2 = new Panel(); crashPanel2.add( dontCrashButton ); crashPanel.add( crashPanel1 ); crashPanel.add( crashPanel2 ); add( crashPanel, BorderLayout.SOUTH ); setVisible( true ); tf1.requestFocus(); } // * // * TextListener // * public void textValueChanged( TextEvent e ) { System.out.println( "Text = " + tf1.getText() ); try { if( e.getSource().equals( tf1 ) ) { tf1.removeTextListener( this ); System.out.println( "Clear the field except for first char." ); tf1.setText( tf1.getText().substring(0,1) ); if( isCrash ) { System.out.println( "Set the cursor/caret." ); tf1.setCaretPosition(1); //Gen's an NPE in IE4. } else { System.out.println( "Don't set the cursor/caret." ); } System.out.println( "Exit the try/catch." ); //tf1.addTextListener( this ); // no good here. } } catch( Exception ee ) // for bad index. { // doesn't catch other NPE. } } public void keyPressed( KeyEvent e ) { } public void keyReleased( KeyEvent e ) { } // * // * ActionListener // * public void actionPerformed( ActionEvent e ) { if( e.getSource().equals( dontCrashButton )) { isCrash = false; crashButton.setLabel( "Do a setCaretPosition()" ); dontCrashButton.setLabel( "Don't do a setCaretPosition() - active" ); tf1.requestFocus(); tf1.addTextListener( this ); // no good. } else if( e.getSource().equals( crashButton )) { isCrash = true; crashButton.setLabel( "Do a setCaretPosition() - active" ); dontCrashButton.setLabel( "Don't do a setCaretPosition()" ); tf1.requestFocus(); tf1.addTextListener( this ); // no good. } } public void destroy() { removeAll(); } }