event

Keymap and KeyStroke example

With this example we are going to see how to use Keymap and KeyStroke classes in a Java. These classes are useful when you want to bind a certain key stroke with the default button of the window.

In order to work with Keymap and KeyStroke:

  • Use KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false) method to get the “Enter” key stroke.
  • Use Keymap.removeKeyStrokeBinding to remove a stroke from the keymap.
  • Now you can go ahead an do JFrame.getRootPane().setDefaultButton(defaultButton) to set the default button of the window. The default button will be now pressed when you hit the “Enter” button.

Let’s see the code snippet that follows:

package com.javacodegeeks.snippets.desktop;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.Keymap;

public class DefaultSample {

    private static void showUI() {

  JFrame jFrame = new JFrame("");

  jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  Container container = jFrame.getContentPane();

  JTextField txt = new JTextField();

  container.add(txt, BorderLayout.NORTH);

  ActionListener actListener = new ActionListener() {

@Override

public void actionPerformed(ActionEvent event) {

    System.out.println(event.getActionCommand() + " selected");

}

  };

  JPanel jPane = new JPanel();

  JButton defaultButton = new JButton("Hit Enter");

  defaultButton.addActionListener(actListener);

  jPane.add(defaultButton);

  JButton otherButton = new JButton("Onother Button");

  otherButton.addActionListener(actListener);

  jPane.add(otherButton);

  container.add(jPane, BorderLayout.SOUTH);

  Keymap map = txt.getKeymap();

  KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false);

  map.removeKeyStrokeBinding(stroke);

  jFrame.getRootPane().setDefaultButton(defaultButton);

  jFrame.setSize(350, 250);

  jFrame.setVisible(true);
    }

    public static void main(String args[]) {

  javax.swing.SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

    showUI();

}

  });
    }
}

 
This was Keymap and KeyStroke example

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