I need to check user input in realtime. So when the user has entered more than for example 40 characters, he will be sent to the next line. I tried to use getText method in onKeyReleased method, but when the user hold the key, it can enter more than 40 characters. Sorry, maybe the explanation is not good enough.
Maybe what you are looking is something like that:
/* [Code...] */
#FXML
private void initialize() {
firstField.textProperty().addListener((observable, oldValue, newValue) -> {
if (newValue.length() > 40)
secondField.requestFocus();
});
}
/* [Code..] */
Need to do the changes on the Controller class.
As Sendrick suggested on the link this.
Related
So I have probably an easy question, but I couldn't find anyone asking this question on Google, so now I'm here.
The problem is simple - I must copy a line of text that has white spaces and tabulators in it, but once I copy it inside my text (input) field, it removes all the tabulators for some reason, so it leave the text all in one big mess that I cannot filter anything out of it.
Any ideas what could be done so those input fields would allow tabulators?
P.S. By pressing tab while I'm inside the input field, it moves between the buttons, instead of inputting a tabulator.
The content of a TextField is represented by a private static class TextFieldContent. TextFieldContent implements insert(int index, String text, boolean notifyListeners) method to filter the input text. The method uses a static method from TextInputControl class to remove "illegal" characters, here is the implementation:
#Override
public void insert(int index, String text, boolean notifyListeners) {
text = TextInputControl.filterInput(text, true, true);
if (!text.isEmpty()) {
characters.insert(index, text);
if (notifyListeners) {
ExpressionHelper.fireValueChangedEvent(helper);
}
}
}
The last parameter in TextInputControl.filterInput(text, true, true) defines whether tab characters are "illegal" or not. It's set to true and as I mentioned before, that class is a private static final class and you can't extend it and override insert method.
The solution is to extend TextInputControl and create a custom Content class that doesn't remove tab characters.
As an alternative, you can use TextArea, text areas accept tab characters.
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.
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?
I have field in which only Alphanumeric values are allowed. I need to check a scenario where user could enter capital letter using "shift" key (OKAY)
SHIFT+a =A
Also a possibility junk characters can be entered using "shift" key (NOT OKAY), like
SHIFT+1 = !
How do I put a validation in a way that only characters are allowed if "SHIFT" key is pressed?
if(NativeEvent.getShiftKey()){
...........
}
If you want to detect pressed keys, you can use a KeyUpHandler or KeyDownHandler.
TextBox t = new TextBox();
t.addKeyUpHandler(new KeyUpHandler() {
#Override
public void onKeyUp(KeyUpEvent event) {
int pressedKey = event.getNativeKeyCode();
}
});
You can use the "pressedKey" integer to see what key code user pressed. Also interesting is KeyCodes, which has the codes for special keys.
If you want to validate user input instead, the easiest way is with HTML5 form validation. To implement that method, you can set up your field like this:
TextBox t = new TextBox();
t.getElement().setAttribute("required", "required");
t.getElement().setAttribute("pattern", "[a-zA-Z0-9]+");
Here's another resource for HTML5 form validation. And another.
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.