Disable An Input Character In Java | Free Source Code

Disable an Input Character in Java

disable

In this tutorial will teach you how to build a program that will disable a specific input of a character in java.


So, now let’s start this tutorial!

1. Open JCreator or NetBeans and make a java program with a file name of disableInputChar.java.

2. Import the swing package library:

import javax.swing.*; // used to access the JComponent,JFrame,JTextField, and KeyStroke class

3. We will initialize variables in our Main, variable frame as JFrame and txtField as JTextField.

JFrame frame = new JFrame("Disable an Inputted Character");
JTextField txtField = new JTextField(15);

4. To disable an input character getInputMap method of the textfield with its keystroke that has the typed character and the “none” function, means not to include in the textfield.

txtField.getInputMap(JComponent.WHEN_FOCUSED).put(
    KeyStroke.getKeyStroke("typed a"), "none");
 
txtField.getInputMap(JComponent.WHEN_FOCUSED).put(
    KeyStroke.getKeyStroke("typed 3"), "none");

As what you can see the code above, the keyword “typed a” here shows that when we type letter ‘a’ to the keyboard in the textfield there is a certain action that is invoked. We have put its partner to “none”, it means there is no certain action to be invoked and you cannot type this letter in the textfield. The same goes for number 3.

5. Finally, add the textfield, set the size, visibility, and the close operation of the frame. Copy this code below:

frame.getContentPane().add(txtField);
frame.setSize(300, 300);
frame.setVisible(true);

Output:

output


Here’s the full code of this tutorial:

import javax.swing.*; // used to access the JComponent,JFrame,JTextField, and KeyStroke class
 
public class disableInputChar {
  public static void main(String[] argv) {
  	JFrame frame = new JFrame("Disable an Inputted Character");
    JTextField txtField = new JTextField(15);
 
 
    txtField.getInputMap(JComponent.WHEN_FOCUSED).put(
        KeyStroke.getKeyStroke("typed a"), "none");
 
    txtField.getInputMap(JComponent.WHEN_FOCUSED).put(
        KeyStroke.getKeyStroke("typed 3"), "none");
 
    frame.getContentPane().add(txtField);
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
Download Code
Facebook Comments

Leave a Reply

Your email address will not be published.