Home » Desktop Java » awt » event » Focus change example

About Ilias Tsagklis

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

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);

jButton.addActionListener(actListner);

jButton.addMouseListener(mListener);

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

    jButton.setRequestFocusEnabled(false);

}

cPane.add(jButton);

  }

  jFrame.setSize(400, 300);

  jFrame.setVisible(true);
    }
}

class FocusMove implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent event) {

  Object src = event.getSource();

  if (src instanceof Component) {

Component comp = (Component) src;

comp.transferFocus();

  }
    }
}

class MouseFocusMove extends MouseAdapter {

    @Override
    public void mouseEntered(MouseEvent event) {

  Component cmp = event.getComponent();

  if (!cmp.hasFocus()) {

cmp.requestFocus();

  }
    }
}

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

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of