Jump to Real's How-to Main page

Make sure that my jTextfield has the focus when a JFrame is created

In a JFrame, use a small WindowAdapter to listen to the WindowOpened event. From there, simply request the focus for the JTextfield. This is not needed with the Appletviewer or in Application, but with some browsers (like Netscape), you need to do it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MyFrame extends JFrame {

JTextField field1;
JTextField field2;
JPanel panel;

 public MyFrame() {
  super( "This is my Frame" );
  panel = new JPanel();
  field1 = new JTextField( 10 );
  field2 = new JTextField( 10 );
  panel.add( new JLabel("Field 1:"));
  panel.add( field1 );
  panel.add( new JLabel("Field 2:"));
  panel.add( field2 );
  getContentPane().add( "Center", panel );
  addWindowListener( new WindowAdapter() {
   public void windowOpened( WindowEvent e ){
        field1.requestFocus();
     }
   } ); 
  pack();
  setVisible( true );
  }

}
To try it :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MyFrameApplet extends JApplet {
public void init() {
  MyFrame myFrame = new MyFrame();
  }
}

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]