awt
Key event listener to capitalize letter keys example
In this example we shall show you how to use KeyEventDispatcher
interfacce in order to create a simple application that capitalizes key letters on the fly in a Java Desktop Application. You might find this particularly usefull when you want your application to ignore the case of text input. Additionally, you can use these template and the basic techniques to do more things in your application. like on the fly correction or word suggestion.
In short, all you have to do to use the KeyEventDispatcher
to capitalize letters is:
- Create a new
KeyEventDispatcher
instance. This component will intercept all key events prior sending them to the focused component. - Override
dispatchKeyEvent
. Now every time the user presses a key, this method will fire up. - Use
KeyEvent.KEY_TYPED
to identify the key that was pressed. - Use
KeyEvent.setKeyChar(Character.toUpperCase(KeyEvent.getKeyChar()))
to set the letter to upper case.
Let’s see the code:
package com.javacodegeeks.snippets.desktop; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Component; import java.awt.Frame; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.TextArea; import java.awt.event.KeyEvent; public class KeyEventListener { public static void main(String[] args) { // Intercept all key events prior sending them to the focused component KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { // This example converts all typed keys to upper case if (e.getID() == KeyEvent.KEY_TYPED) { e.setKeyChar(Character.toUpperCase(e.getKeyChar())); } // setting discardEvent to true will not forward the key event to the focused component boolean discardEvent = false; return discardEvent; } }); // Create frame with specific title Frame frame = new Frame("Example Frame"); // Create a component to add to the frame; in this case a text area with sample text Component textArea = new TextArea("Sample text..."); // Create a component to add to the frame; in this case a button Component button = new Button("Click Me!!"); // Add the components to the frame; by default, the frame has a border layout frame.add(textArea, BorderLayout.NORTH); frame.add(button, BorderLayout.SOUTH); // Show the frame int width = 300; int height = 300; frame.setSize(width, height); frame.setVisible(true); } }
This was an example on how to use a key event listener to capitalize letter keys.
Recomendation very good. Efficient code !