event

GetFocusTraversalKeys example

In this example we are going to see how to get the focus traversal keys of an input device in a Java Desktop Application.

This is quite simple and to do it you have to follows these steps

  • Create an input device like an JButton.
  • Create a new HashSet to hold AWTKeyStroke objects.
  • Use the JButton.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS) call to get the FocusTraversalKeys of that input device.
  • Use JButton.add(KeyStroke.getKeyStroke("P")) to add a keystroke to the button.
  • Use the JButton.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, s) to set FocusTraversalKeys of these device.

Let’s see the code:

package com.javacodegeeks.snippets.desktop;

import java.awt.AWTKeyStroke;
import java.awt.KeyboardFocusManager;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.KeyStroke;

public class Main {

    public static void main(String[] argv) throws Exception {

  JButton jButton = new JButton("a");

  Set<AWTKeyStroke> s = new HashSet<AWTKeyStroke>(jButton.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));

  s.add(KeyStroke.getKeyStroke("P"));

  jButton.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, s);

    }
}

 
This was an example on how to get FocusTraversalKeys 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