Is there a way to ignore backspace key in java? [duplicate] - java

This question already has answers here:
How to detect backspace in a keyTypedEvent
(3 answers)
Closed 5 years ago.
Whenever I press backspace in the text box this code is triggered.
private void txtAgeKeyTyped(java.awt.event.KeyEvent evt) {
char agetext= evt.getKeyChar();
if(!(Character.isDigit(agetext))){
evt.consume();
JOptionPane.showMessageDialog(null,"Age is only written in Numbers!");
}
}
It should only be triggered if I typed Alphabets instead of Numbers only.
For some reason it is triggering whenever I press the Backspace Key.
Is there a way for me to use backspace without triggering this block of code?
I'm sorry this is the first time i fiddled with Key Events

The backspace character is just \b. As you can see, the VK_BACK_SPACE constant is defined like this:
public static final int VK_BACK_SPACE = '\b';
The constant is defined in the java.awt.event.KeyEvent class btw. If you use IntelliJ it will automatically and statically import it for you.
You can check whether agetext is \b. If it is, return from the method:
private void txtAgeKeyTyped(java.awt.event.KeyEvent evt) {
char agetext= evt.getKeyChar();
if (agetext == VK_BACK_SPACE) return;
if(!(Character.isDigit(agetext))){
evt.consume();
JOptionPane.showMessageDialog(null,"Age is only written in Numbers!");
}
}

Related

Having trouble clearing a text field when an improper character is entered

I am trying to retrieve the values from a JTextField on a keypress to do something if the values are integers and to clear the field if the values are not integers. Every time I try to retrieve the value, I am getting the value entered before that(if I enter 12 I get 1 back then if I enter 123 I get 12 back) and when I try to clear the field on an invalid character everything but the invalid character gets cleared?
public void setUpListeners()
{
JTextField jT [] = myV.getTextFields();
jT[0].addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e){
int id = e.getID();
if (id == KeyEvent.KEY_TYPED)
{
char c = e.getKeyChar();
try
{
//check if chars entered are numbers
int temp = Integer.parseInt(String.valueOf(c));
String tempS = jT[0].getText();
System.out.println(tempS);
}
catch(Exception ex)
{
jT[0].setText("");
System.out.println("Not an integer");
}
}
}
});
}
You could do the following:
public static boolean validateNumber(char num){
return (num >= '0' && num <='9');
}
And then use parameter KeyEvent "e":
if(!validateNumber(e.getKeyChar()))
e.consume();
And instead of using
public void keyTyped(KeyEvent e){
use
public void keyReleased(KeyEvent e){
I think you will get what you need, I hope I have helped you ;)
Swing components use Model-View-Controller (MVC) [software] design pattern / architecture. The model holds the data. For a JTextField the data is the text it displays. The default model for JTextField is PlainDocument, however JTextField code actually refers to the Document interface which PlainDocument implements.
Look at the code for method getText() in class JTextComponent (which is the superclass for JTextField) and you will see that it retrieves the text from the Document.
When you type a key in JTextField, the character gets passed to the Document. It would appear that your keyTyped() method is invoked before the character you typed reaches the Document, hence when you call getText() in your keyTyped() method, you're getting all the text apart from the last character you typed.
That's one of the reasons not to use a KeyListener in order to validate the text entered into a JTextField. The correct way is detailed in the question that tenorsax provided a link to in his comment to your question.
Apart from DocumentFilter or JFormattedTextField (or even InputVerifier), you can add an ActionListener to JTextField which will execute when you hit Enter in the JTextField. You will find many on-line examples of how to implement each one of these options, including the link provided in tenorsax comment.

Handling (consuming) key press

I started playing with java a little bit, after few years of coding in C#. What I am trying to achieve is to handle a key press event for jTextField.
In C# i would code:
e.Handled = true;
I did a little research and read that I can use consume() in java. So i wrote the following code:
if (evt.getKeyChar() == '.' || DataController.getInstance().isDot_pressed())
{
jTextFieldQuery.setText(DataController.getInstance().generateText(jTextFieldQuery.getText()));
if(evt.getKeyChar()!='.')
{
DataController.getInstance().setOdgovor(DataController.getInstance().getOdgovor()+evt.getKeyChar());
}
else
{
DataController.getInstance().setDot_pressed(!DataController.getInstance().isDot_pressed());
}
evt.consume();
}
}
This code should handle key pres for "." and every key press until another "." is pressed in the mean time it loads predefined text in text field.
This solution doesn't work, it consumes(handles) for example delete button but it doesn't handle normal letters.
Any suggestions? Thanks.

KeyListener- wish to input only number, but it let me input a letter [duplicate]

This question already has answers here:
Restricting JTextField input to Integers [duplicate]
(6 answers)
Closed 7 years ago.
I use this code to restrict the input only for numbers, but if the first key I press is a letter, the code let me enter that letter, only one time, then when I erase it I cannot input anymore letters, what is wrong with the code? I want to imput only numbers.
amount.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!(Character.isDigit(c)))
e.consume();
}
});
I added the two closing parentheses, still the same results, here is a
video
Try this:
try{
Double.parseDouble(c);
//Code here for TRUE case (Is Number)
}catch(NumberFormatException e1){
//Code here for FALSE case (Is NOT Number)
}

How to perform an action when only first key pressed?

I want a JTextFeild event when keyboard button pressed.I want concatenate "ADZ" text to the front whole text.(If we enter "2" whole text should be "ADZ2") THe Action will performed only first key press.After any key pressing action won't be performed.Action will performed only once.
I tried below code,but if type 22 it gives"ADZADZ22".
private void JTextFeild1KeyTyped(java.awt.event.KeyEvent evt) {
String num1 = JTextFeild1.getText();
JTextFeild1.setText("ADZ"+num1);
I want this if type 22, it will gives ADZ22.
A simple way to solve it, is to check if the prefix is already there.
This avoids that the same prefix is added twice.
private void JTextFeild1KeyTyped(java.awt.event.KeyEvent evt) {
String num1 = JTextFeild1.getText();
if (!num1.startsWith("ADZ"))
{
num1 = "ADZ" + num1;
JTextFeild1.setText(num1);
}
...
}
Please note: Java coding rules would suggest to make field names (e.g. jTextField) start with a lower case character. The same goes for method names (e.g. private void jTextField1KeyTyped)
public static int counter = 0;
Maintain a static counter at class level. At key press increase it by one. check :
if(counter == 1) {
// do your operation
}
Check if your JTextField is empty and then set a prefix. This method sets "ADZ" when the field is empty and you type something and then appends everything you type.
public void keyTyped(KeyEvent ke) {
if(txfInput.getText().equals("")) {
txfInput.setText("ADZ");
}
}

How to limit user to input only numbers?

I am currently creating this java GUI that will ask the user to input 10 entries, then use the values to execte the next action.
I want only numbers or decimal point to be inputted inside such that it can only be a float value.
If it is not number or decimal point, it should prompt the user to input that specific entry again before the next action is executed.
How should I do it?
Wong,
not sure whether you are using Swing or not...
Ages ago I had the same problem and I solved it with creating a class RestrictedTextField extending JTextField. In the constructor I added a key listener (addKeyListener(new RestrictedKeyAdapter());)
private class RestrictedKeyAdapter extends KeyAdapter {
#Override
public void keyReleased(KeyEvent e) {
if (getText().equals("")) {
oldString = "";
return;
} else {
// if you cannot parse the string as an int, or float,
// then change the text to the text before (means: ignore
// the user input)
try {
if (type.equals("int")) {
int i = Integer.parseInt(getText());
oldString = getText();
} else if (type.equals("float")) {
float f = Float.parseFloat(getText());
oldString = getText();
} else {
// do nothing
}
} catch (NumberFormatException el) {
setText(oldString);
}
// if the text is identical to the initial text of this
// textfield paint it yellow. If the text was changed
// paint it red.
if (initialString.equals(getText())) {
setForeground(Color.YELLOW);
} else {
setForeground(Color.RED);
}
}
}
}
The idea is, that every time the user presses a key in the textfield (and releases it then), the text in the textfield is parsed. If the component should accept only floats for example then the component tries to parse it as an float (Float.parseFloat(..)). If this parsing is successful everything is fine. If the parsing fails (an NumberFormatException is thrown) then the old text is written back into the textfield (literally ignoring the user input).
I think you can add the KeyAdapter directly to the JTextField without creating a dedicated class for that, but with this solution you can remember the initial string and the old string.
you can play around with the code.. you can change the colour of the textfield if the input is valid or not (or like in my code snippet if the text is identical to the initial string).
one additional comment: I set the 'type' of the textfield in a variable with the name 'type', which is simply a String with the values "int", "float", etc.... a better solution would be here for example an enum of course...
I hope this is helpful...
timo
There are various options for what you would like to do. You can check here for one example of doing so. Another example could be to use Formatted TextFields, as shown here.
On the other hand, upon submission, you can try to parse the value to a float or double. If you get any exceptions, then, the value is not a number.
Lastly, you can use Regular Expressions. An expression such as ^\\d+(\\.\\d+)?$ should match any integer or floating point number.

Categories

Resources