Manage focus with Swing in Java

1. Introduction

The focus is the “selected” state of a component. The component who has the focus is the active component. It’s possible to ask focus fror a specific component but normally this is perfectly managed by Swing.

With this tutorial, you will learn how to ask focus for a specific component and how to define an order of focus. We will also learn a bit about the validation of input fields, the focus listen and the utility of KeyboardFocusManager.

2. Ask focus

Normally, the focus is managed by a component on the mouse click or when we come to a component with keyboard. A component who is focused is often visually modified, with a special border or an other background color.

To manage the focus of the windows, it’s a little bit different and depends of the operating system, but nothing can give you the guarantee to have focus. On Windows, you can obtain focus on a window using toFront but nothing is guraranteed.

For the components, you can use the requestFocusInWindow() method :

component.requestFocusInWindow();

To obtain the focus, you have to ask focus after the add of the component but before the display of the window.

Before Java 1.4, you needed to use the requestFocus() method, but now it is not a good idea to use it, because it give also focus to the window of the component, and that’s not always possible.