last character added in textbox - java

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.

Related

do while loop validation and try again

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.

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.

add a special character to a text field in javafx

I want to add a special character to a textfield .
For example I want to add / automatically between a date that user typed.
Or adding some space between some digits in a number .like this: "2020 2020 2020 2020"
I used this code but it doesn't work correctly .
textfield.textProperty().addListener(new ChangeListener<String>(){
#Override
public void changed(ObservableValue<? extends String> ov, String t, String t1) {
if(t1.length()==4 || t1.length()==9 || t1.length()==14){
textfield.setText(t1+" ");
System.out.println("space added");
}
}
}
It's adding the space just fine. I think the issue is that you want to move the carat position after adding the extra text. You can use textfield.getCaratPosition() to find the current position and textfield.positionCarat(...) to change it.
The logic is going to be quite complex though and depends greatly on what the user is doing and precisely how you want the text field to behave. E.g. what if the text is changing because the user deletes something? What about copy and paste?

if statement erroron button click

can someone please help making pairs game and using this if statement can someone tell me if theres a bracket or semi colon missing cant see whats missing (pic2.getTag() == beck) is underlined have 4 buttons want to pair or reset them the buttons start with set tag name (boots) this works but no good for non match
This works
if (pic2.getTag() == pic1.getTag()){
pic1.setVisibility(View.INVISIBLE);
pic2.setVisibility(View.INVISIBLE);}
THis doesnt
pic1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pic1.setTag(beck);
pic1.setBackgroundResource(R.drawable.becks);
if (pic2.getTag() == beck) {
pic1.setVisibility(View.INVISIBLE);
pic2.setVisibility(View.INVISIBLE);
}
}
});
The problem is in the compare operator ==. View tags are Objects (most probably Strings), so you need to compare them with equals.-
if (pic2.getTag().equals(pic1.getTag()))
and
if (pic2.getTag().equals(beck))

Categories

Resources