What will be the FormatterFactory's factor value in JFormattedTextField if I only want to accept letters and spaces.
Cause I want it to accepts Names only. Like - John Doe.
I couldn't find an elegant way using a formatter. The non-elegant way is to create a MaskFormatter with the main issue that you will be limiting the number of characters allowed (although you can limit to an arbitrarily large number).
MaskFormatter mask = new MaskFormatter("*************"); // Specifies the number of characters allowed.
mask.setValidCharacters("qwertyuiopasdfghjklzxcvbnm" +
" QWERTYUIOPASDFGHJKLZXCVBNM "); // Specifies the valid characters: a-z, A-Z and space.
mask.setPlaceholderCharacter(' '); // If the input is less characters than the mask, the space character will be used to fill the rest. Then you can use the trim method in String to get rid of them.
JFormattedTextField textField = new JFormattedTextField(mask);
I feel that validating the input is a better approach than restricting characters in this case. I can add an example if you want to use this approach.
Edit: Using InputVerifier, you have to subclass it and override verify as shown below.
JTextField textField = new JTextField();
textField.setInputVerifier(new InputVerifier() {
#Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
if (text.matches("[a-zA-Z ]+")) // Reads: "Any of a-z or A-Z or space one or more times (together, not each)" ---> blank field or field containing anything other than those will return false.
return true;
return false;
}
});
The text field will not yield focus (except to parent components) until requirements are met.
Related
When compare two values in Jtextfield it is coming error when space also including it is showing correct. But without using it is showing error. for example in JTextfield1 it is "abcd" when in JTextfield2 "abcd " to show the message correct else it is showing error.
But I want to show if JTextfield1 is showing is "abcd" and same in jTextfield2 also same as "abcd" then show the message correct else it is false in jLabel.
my code is as follows
private void jTextField2KeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if (jTextField1.getText().equals(jTextField2.getText()))
{
jLabel1.setText("sucess");
}
else
{
jLabel1.setText("fail");
}
}
when space also including it is showing correct.
Use this to avoid spaces
if (jTextField1.getText().trim().equals(jTextField2.getText().trim()))
From the doc public String trim()
Returns a copy of the string, with leading and trailing whitespace
omitted. If this String object represents an empty character sequence,
or the first and last characters of character sequence represented by
this String object both have codes greater than '\u0020' (the space
character), then a reference to this String object is returned.
Otherwise, if there is no character with a code greater than '\u0020'
in the string, then a new String object representing an empty string
is created and returned.
Well, I'm trying to replace a word by using contains() Method:
String z = tfB.getText().toString();
String show = textPane.getText().toString();
if(show.contains(z)){
// how I specify the word that were found and change it without
effecting anything with in that line
}
well what I main by that:
What I'm trying to do is get the value from the user.
then search if it found replace it with something. For example:
String x = "one two three four five";
It should set the textPane to "one two 3 four five"
or
"one two 3-three-3 four five"
could any one please tell me how to do it.
Thank you
What I'm trying to do is get the value from the user. then search if it found replace it with something.
Don't use the contains() method because you will need to search the text twice:
once to see if the text is found in the string
again to replace the text with a new string.
Instead, use the String.indexof(...) method. It will return the index of the text IF it is found in the String.
Then you should replace the text directly in the Document of the text pane, not in the String itself. So the code would be something like:
int length = textPane.getDocument().getLength();
String text = textPane.getDocument().getText(0, length);
String search = "abc...";
int offset = text.indexOf(search);
if (offset != -1)
{
textPane.setSelectionStart(offset);
textPane.setSelectionEnd(offset + search.length();
textPane.replaceSelection("123...");
}
Also, not that you get the text from the Document, not the text pane. This is to make sure the offsets are correct when you replace the text in the Document. Check out Text and New Lines for more information on why this is important.
Wrote a method which takes in a String and checks to see the follow conditions:
If String is "quit", it will terminate the program.
If the String is any value other than an integer, it should return "Invalid input ".
Any negative integers and also 0 should return "Invalid input".
However, when I passed in 10, it returned as "Invalid input"?
Please advise:
public static String validate(String input) {
Pattern pattern = Pattern.compile(".*[^1-9].*");
StringBuilder results = new StringBuilder();
if (input.equals("quit")) {
System.exit(1);
} else if (!pattern.matcher(input).matches() == false) {
results.append("Invalid input ");
results.append("'");
results.append(input);
results.append("'");
}
return results.toString();
}
What's wrong with what I am doing?
You should write a pattern of what you expect instead of what you're not.
As describe what you want is always simpler that describe the rest of it.
So you expect :
Pattern acceptPattern = Pattern.compile("[1-9][0-9]*");
You may consider make you conditional expression simpler and correct by not using both ! and == false at the same time:
Which will make :
if (!acceptPattern .matcher(input).matches()) {//Invalid input code}
or
if (acceptPattern .matcher(input).matches() == false) {//Invalid input code}
note :
You write if(!A == false) => if(A == true) => if(A) but which was the inverse
It looks like you want to match one or more digits, where the first one is not a zero.
[1-9]\d*
If you want to force it to be the entire string, you can add anchors, like this:
^[1-9]\d*$
Your regex string doesn't allow for the presence of a zero (not just a lone zero).
That is, the string ".*[^1-9].*" is looking for "any number of characters, something that isn't 1-9, and any number of characters". When it finds the zero, it gives you your incorrect result.
Check out What is the regex for "Any positive integer, excluding 0" for how to change this.
Probably the most helpful solution on that page is the regex [0-9]*[1-9][0-9]* (for a valid integer). This allows for leading zeros and/or internal zeros, both of which could be present in a valid integer. In using Matcher#matches you also ensure that this regex matches the whole input, not just part of it (without the need to add in beginning and end anchors -- ^$).
Also, the line else if (!pattern.matcher(input).matches() == false) could be made a lot more clear.... maybe try else if (pattern.matcher(input).matches()) instead?
I'm making a word guessing game. The JTextField can't be empty, can't be longer or smaller than 5 and cannot contain numbers. How do I do the last part?
#Override
public void actionPerformed(ActionEvent e) {
if (text.getText().isEmpty()) {
showErrorMessage("You have to type something");
} else if (text.getText().length() != 5) {
showErrorMessage("Currently only supporting 5-letter words");
} else if (contains integer){
showErrorMessage("Words don't contain numbers!");
} else {
r.setGuess(text.getText());
}
}
Rather than explicitly checking for numbers, I would suggest whitelisting characters which are allowed. Would letters with accents be allowed, for example? Both upper and lower case? Punctuation?
Once you've worked out your requirements, I suggest you express them as a regular expression - and then check whether the text matches the regular expression.
For example:
private static final Pattern VALID_WORD = Pattern.compile("^[A-Za-z]*$");
...
if (!VALID_WORD.matcher(text.getText()).matches()) {
// Show some appropriate error message
}
Note that I haven't included length checks in there, as you're already covering those - and it may well be worth doing so in order to give more specific error messages.
You might also want to consider preventing your text box from accepting the invalid characters to start with - just reject the key presses, rather than waiting for a submission event. (You could also change the case consistently at the same time, for example.) As noted in comments, JFormattedTextField is probably a good match - see the tutorial to get started.
create a method that checks if the JTextField has a number like this:
private boolean isContainInt(JTextField field) {
Pattern pt = Pattern.compile("\\d+");
Matcher mt = pt.matcher(field.getText());
return mt.find();
}
if (!text.getText().matches("[a-zA-Z]*")) {
// something wrong
}
I was wondering if there's a simple way to deal with escape characters in a JTextField. The thing is that getText() will escape the escape character. Of course, that will be the preferred behavior most of the time, but not if you want to allow the users to freely provide a delimiter for a CSV file (including \t). Any ideas?
Bob
You can always override the behavior of any and all public functions in a swing component. Its called "specialization". For example, you can create your own MyJTextField class and override the getText() method.
JTextField is only a View so it always has a model inside it, this model is Document class. You can try this:
JTextField f = new JTextField();
// your JTextField is being filled somehow with text ...
Document document = f.getDocument();
try {
String text = document.getText(0, document.getLength());
} catch (BadLocationException ex) {
}
Maybe when you collect text from Document instance instead of JTextField instance it won't be escaped;
I know this may be kind of late for you, but I found an easy solution to that problem:
JTextfield field = new JTextField();
/*someone puts a string into it*/
escapeFulString = field.getText().replace("\\t","\t");
System.out.println(escapeFulString);
This will print out that string with all the tabs. To add any other escape sequences just do that same process.
Just don't forget, java string methods DO NOT edit in place, e.g.:
text.replace("\\t","\t")
//is not the same as
text = text.replace("\\t","\t");