Java KeyboardFocusManager .focusNextComponent ()

Syntax

KeyboardFocusManager.focusNextComponent() has the following syntax.

public final void focusNextComponent()

Example

In the following code shows how to use KeyboardFocusManager.focusNextComponent() method.


/*ww  w. j a va 2  s  .c  o m*/
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {

  public static void main(String args[]) {
    JFrame frame = new JFrame("Focus Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ActionListener actionListener = new ActionFocusMover();
    MouseListener mouseListener = new MouseEnterFocusMover();

    frame.setLayout(new GridLayout(3, 3));
    for (int i = 1; i < 10; i++) {
      JButton button = new JButton(Integer.toString(i));
      button.addActionListener(actionListener);
      button.addMouseListener(mouseListener);
      if ((i % 2) != 0) {
        button.setFocusable(false);
      }
      frame.add(button);
    }

    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

class ActionFocusMover implements ActionListener {
  public void actionPerformed(ActionEvent actionEvent) {
    KeyboardFocusManager manager = KeyboardFocusManager
        .getCurrentKeyboardFocusManager();
    manager.focusNextComponent();
  }
}

class MouseEnterFocusMover extends MouseAdapter {
  public void mouseEntered(MouseEvent mouseEvent) {
    Component component = mouseEvent.getComponent();
    if (!component.hasFocus()) {
      component.requestFocusInWindow();
    }
  }
}




















Home »
  Java Tutorial »
    java.awt »




BasicStroke
BorderLayout
CardLayout
Color
Cursor
Desktop
DesktopManager
DisplayMode
EventQueue
FlowLayout
FocusTraversalPolicy
Font
FontMetrics
GradientPaint
Graphics
Graphics2D
GraphicsConfiguration
GraphicsDevice
GraphicsEnvironment
GridBagConstraints
GridBagLayout
GridLayout
Image
ItemSelectable
KeyboardFocusManager
LayoutManager
LayoutManager2
Point
Rectangle
Robot
Shape
SplashScreen
SystemColor
SystemTray
TexturePaint
TrayIcon
Toolkit
Transparency