event

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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He 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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button