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.
Related
I'm fairly new to java and was wondering how would one force a user to enter a valid option in a do...while loop?
What i'm trying to achieve here is to display a menu for as long as the user does not select the exit option which is '4' in my case (it's a char not an int). But if the selection is invalid I want to display an error message and prompt the user to make a new selection, this time, without displaying the menu again.
So far, inside my do...while loop i'm displaying different information according to the user selection. If they enter anything other than 1-4, they end up in my last else if which displays an error message, but at the same time they leave the if/else if loop and end up back in the main menu.
Don't know if this is clear but any help would be appreciated. I also tried the same thing with switch but got the same problem.
Thanks.
do {
// display main menu
if (menu == '1') { ... }
else if (menu == '2') { ... }
else if (menu == '3') { ... }
else if (menu == '4') { ... }
else if (menu != '4') { // display error message }
} while (menu != '4')
Okay, so you have a job which we can describe in a self-contained fashion with a short list of clearly stated parameters:
Ask the user for input.
Check that the input is valid.
If not, keep asking.
That's it. That's a job we can write. Easily at that.
So, do that! Make a method to do just this job. There's only one parameter you need, which is: "What constitutes valid input". If we can simplify that we just need a character, and everything from '1' to this char is valid, then:
public char askUser(char maxValid) {
do {
char in = askUserForInput(); // however you get that char.
if (in >= '1' || in <= maxValid) return in;
System.out.println("Enter a value between 1 and " + maxValid + "> ");
} while (true);
}
Then you can just call this method when you need input.
You can roll this logic (so, that'd be a do/while loop inside your do/while loop) into the main loop, but two rather significant aspects of writing good code is to find easily isolatable aspects and to, well, isolate them (be it making new methods, types, modules, or subsystems - it applies across the entire hierarchy), and to avoid repeating yourself.
I Am tring to do a bot that you put instruccions like say: hello
But when I try to use
robot.keyPress(KeyEvent.VK_BRACELEFT);
or
robot.keyPress(221);
one or the other should press: {
but no it throws me the exception of an invaid key code.
So can anyone tell me how to type: { and }
You would need to use shift and the key that is there underneath it. The Robot class doesn't reach all ascii characters. Here is an example:
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_OPEN_BRACKET);
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_OPEN_BRACKET);
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!");
}
}
I have created a my KeyListener for my textbox
txtEmail.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
if(event.getUnicodeCharCode() == 32 || event.getUnicodeCharCode() == 44) {
myFunction();
txtEmail.setText("");
txtEmail.setFocus(true);
}
}
});
myFunction() just computing some value, event.getUnicodeCharCode() == 32 is SPACE and event.getUnicodeCharCode() == 44 is COMMA. so when the user presses space or comma, it will go to my function.
the problem is after the function the textbox should be empty, but it is not, if the user presses space to go to the function, after it, the textbox will contain space in the beginning, and comma if the user presses comma last..
sorry for my bad English, but i hope somebody understand my problem, thank you very much, any help will be greatly appreciated.
Read this manual for KeyEvents
I think you should use the keyReleased-Method, because the method will than be called after the actual event.
In the moment your method will be called before the KeyEvent is done. Thats why you get a space or a comma in the textbox.
The following is code block, where i have been trying to validate jFormatedTextFeild. When a key is typed (any key) code block does seem to execute for the first key typed. But works fine for second key typed ! Please help me :(
private void jFormattedTextField_ByingPriceKeyTyped(KeyEvent evt) {
System.out.println("key typed action ");
String checking = jFormattedTextField_ByingPrice.getText();
Pattern ptrn = Pattern.compile("[A-Z,a-z,&%$##!()*^]");
Matcher match = ptrn.matcher(checking);
if(match.find()){
txtPriceMessage.setVisible(true);
//text field which contains the message does not appears
//for first key typed only it appears when second key is typed.
} else {
txtPriceMessage.setVisible(false);
}
}
Use a DocumentFilter to filter the values going to a text component in real time, that's what it's design for. Take a look at these examples, there's even a PatternFilter for using with regular expressions...
For post validation, use a InputVerifier