awt

Setting the initial focus component in a Window

With this example we shall show you how to set the component that gets the focus when your application starts up. This is very useful when you have many graphical objects firing up at the start up of your application.

Let’s see the code snippet that follows and it should be pretty clear:

 
 
 
 
 

package com.javacodegeeks.snippets.desktop;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;


public class InitialFocusGain {
 
  public static void main(String[] args) {


// Create frame with specific title

Frame frame = new Frame("Example Frame");


// Create a component to add to the frame; in this case a text area with sample text

Component textArea = new TextArea("Sample text...");



// Create a component to add to the frame; in this case a button

Component button = new Button("Click Me!!");


// Add the components to the frame; by default, the frame has a border layout

frame.add(textArea, BorderLayout.NORTH);

frame.add(button, BorderLayout.SOUTH);


// Set component with initial focus; must be done before the frame is made visible

InitialFocusSetter.setInitialFocus(frame, button);


// Show the frame

int width = 300;

int height = 300;

frame.setSize(width, height);

frame.setVisible(true);


  }

  static class InitialFocusSetter {


public static void setInitialFocus(Window w, Component c) {

    w.addWindowListener(new FocusSetter(c));

}


public static class FocusSetter extends WindowAdapter {

    Component initialComponent;

    FocusSetter(Component c) {


  initialComponent = c;

    }

    public void windowOpened(WindowEvent e) {


  initialComponent.requestFocus();



  // This listener is no longer needed so we remove it


  e.getWindow().removeWindowListener(this);

    }

}
  }

}

This was an example on how to set the initial focus component in a Window.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button