Focus change example

In this example we are going to see how to change focus in a Java Application.

All you have to do is:

  • Create a new ActionListener.
  • Override the actionPerformed method.
  • When this method fires up use the transferFocus method to transfer the focus to a specific component.
  • Create a class that extends MouseAdapter.
  • Override the mouseEntered method
  • When this method fires up use the requestFocus method in order to give the focus to the component that is pointed by the mouse.

Let’s see the code snippets that follow:

package com.javacodegeeks.snippets.desktop;

import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {

    public static void main(String args[]) {

  JFrame jFrame = new JFrame("Change Focus Demo");

  ActionListener actListner = new FocusMove();

  MouseListener mListener = new MouseFocusMove();

  Container cPane = jFrame.getContentPane();

  cPane.setLayout(new GridLayout(4, 4));

  for (int c = 1; c < 10; c++) {

JButton jButton = new JButton("" + c);



if ((c % 2) != 0) {





  jFrame.setSize(400, 300);


class FocusMove implements ActionListener {

    public void actionPerformed(ActionEvent event) {

  Object src = event.getSource();

  if (src instanceof Component) {

Component comp = (Component) src;



class MouseFocusMove extends MouseAdapter {

    public void mouseEntered(MouseEvent event) {

  Component cmp = event.getComponent();

  if (!cmp.hasFocus()) {



This was an example on how to handle focus change in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

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

Inline Feedbacks
View all comments
Back to top button