Setting the Initial Focused Component in a Window : Window Event « Swing Event « Java Tutorial






import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] argv) throws Exception {
    JFrame frame = new JFrame();
    JButton component1 = new JButton("1");
    JButton component2 = new JButton("2");
    JButton component3 = new JButton("3");

    frame.setLayout(new FlowLayout());
    frame.add(component1);
    frame.add(component2);
    frame.add(component3);

    InitialFocusSetter.setInitialFocus(frame, component2);

    frame.pack();
    frame.setVisible(true);
  }
}

class InitialFocusSetter {
  public static void setInitialFocus(Window w, Component c) {
    w.addWindowListener(new FocusSetter(c));
  }
}

class FocusSetter extends WindowAdapter {
  Component initComp;

  FocusSetter(Component c) {
    initComp = c;
  }

  public void windowOpened(WindowEvent e) {
    initComp.requestFocus();
    e.getWindow().removeWindowListener(this);
  }
}








15.41.Window Event
15.41.1.The event IDs for the WindowEvent class
15.41.2.Making a Window Handle its Own EventsMaking a Window Handle its Own Events
15.41.3.The WindowListener Interface: events reflecting changes in the state of a window
15.41.4.Using WindowListenerUsing WindowListener
15.41.5.Using Adapter ClassesUsing Adapter Classes
15.41.6.Listens for window iconify and deiconify events, so that it can stop the animation when the window isn't visible.Listens for window iconify and deiconify events, so that it can stop the animation when the window isn't visible.
15.41.7.WindowListener, WindowFocusListener, WindowStateListener
15.41.8.extends WindowAdapter
15.41.9.Handle a window closing event
15.41.10.Setting the Initial Focused Component in a Window
15.41.11.int java.awt.event.WindowEvent.WINDOW_OPENED