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


  Container container = jFrame.getContentPane();

  JTextField txt = new JTextField();

  container.add(txt, BorderLayout.NORTH);

  ActionListener actListener = new ActionListener() {


public void actionPerformed(ActionEvent event) {

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



  JPanel jPane = new JPanel();

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



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



  container.add(jPane, BorderLayout.SOUTH);

  Keymap map = txt.getKeymap();

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



  jFrame.setSize(350, 250);


    public static void main(String args[]) {

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


public void run() {




This was Keymap and KeyStroke example

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

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

I have read and agree to the terms & conditions


Ilias Tsagklis

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button