JTextfield, how to verify content in the getText() method - java

I have a textfield called x.
When the textfield contains " ", I want to do something. If it does not, do something else.
I tried doing
String test = x.getText();
if(test.startsWith(" ")){buttonN.setForeground(Color.GRAY));}
else{buttonN.setForeground(Color.BLACK));}
but it didnt work. any suggestions

Why not use contains?:
if(x.getText().contains("\u0020"))
buttonN.setForeground(Color.GRAY);
else
buttonN.setForeground(Color.BLACK);
Although the aforementioned will work, it won't detect tabular spacing. That being said, I'd recommend using a regular expression instead:
if(Pattern.compile("\\s").matcher(x.getText()).find())
buttonN.setForeground(Color.GRAY);
else
buttonN.setForeground(Color.BLACK);
Reference.

If you just want to ensure if the text field is empty regardless of whether it contains space, tab, newline etc. use the following:
if(x.getText().trim().length() == 0){
buttonN.setForeground(Color.GRAY);
}else{
buttonN.setForeground(Color.BLACK);
}
The String.trim() removes any whitespace in the String.

The easiest solution for any verifycation of the getText() command is this:
If (field.getText().isEmpty()) {
buttonN.setForeground(Color.GRAY);
}
else {
buttonN.setForeground(Color.BLACK);
}

(Color.GRAY)) and (Color.BLACK)) end with 2 closing parenthesis, while only one was opened.
String test = x.getText();
if (test.startsWith (" "))
{
buttonN.setForeground (Color.GRAY);
}
else buttonN.setForeground (Color.BLACK);
Some spaces around parenthesis make the reading more convenient.

Related

How to delete a specific digit from a number written on JLabel in JAVA?

If i have written a number on a JLabel in java, how can I delete a specific digit from it? Is there any option by which I can get the current Cursor position or set it as required and then delete a particular digit of my choice? Kindly help...
You say you want to delete the last digit:
String txt = jLabel.getText();
jLabel.setText(txt.substring(0, txt.length()-1));
This should do the trick.
Edit:
You should also check for null or empty text:
String txt = jLabel.getText();
if(txt != null && !txt.isEmpty()) {
jLabel.setText(txt.substring(0, txt.length()-1));
}
Just delete the last char of the labels text, which is a String, if you are not sure if that String can be null in some cases, catch a NullpointerException.
But always ensure, that the text is not empty when you call substring to prevent a IndexOutOfBoundException:
String text = jLabelObject.getText();
try{
if(!text.isEmpty()){
jLabelObject.setText(text.substring(0, text.length()-1);
}
}catch(NullPointerException e){
jLabelObject.setText("");
}
Please take a look at the Java API Doc
substring(), isEmpty(), length()String
setText() JLabel

Determine if a JTextField contains an integer

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
}

How do you delete a set string from a word (sWord) in Java?

I need help deleting "fe" from sWord in the System.out part of the code. Just need a quick answer on how to do this, its clear that you cant simply subtract it but I don't know how else to do it, thanks for the help. BTW this is not the full code, simply an excerpt.
else if (sWord.substring(sWord.length()-2,sWord.length()).equalsIgnoreCase("fe"))
{
System.out.println("The Plural of" + sWord + "is" + **(sWord-("fe"))** + "ves");
}
If it's only at the end of the string (as in your example), you could do
sWord = sWord.substring(0, sWord.length()-2);
If you want to remove "fe" from anywhere in the sWord you could use,
sWord = sWord.replace("fe", "");
You can use String replace() method:
String newSWord = sWord.replace("fe", "");
If you need some advanced String modification, you can have a look at Apache Commons Lang library - StringUtils replace() method.
How about :
sWord.replace("fe", "");
For more information about replace you can take a look here

How can I trim whitespace by Velocity

I have a method called render_something which can creates a lot of whitespace, for example:
#render_something('xxx')
The result can be:
<a href="#">
something that generate from redner_something
</a>
Which actually I want it to be like this:
something that generate from redner_something
Does velocity has something like this?
#trim(#render_something('xxx'))
I just read this article on Velocity Whitespace Gobbling which suggests a few work-arounds including Velocity Whitespace Truncated By Line Comment.
This basically suggests commenting out line breaks by putting comments at the end of each line. It also suggests not indenting the code in your macros to prevent superfluous (one of my favourite words) spaces occurring.
TBH it's not a great solution but may suit your needs. Simply put ## at the end of each line in your macro and that will make things a little bit nicer... sort of
It seems just java native trim() works.
$someValue.trim() works for me
Solution
In the class where you create the VelocityEngine, add a method as follows
public String trim(String str) {
return str.trim()/*.replace("\n", "").replace("\r", "")*/;
}
then add the following to the VelocityContext that you create:
context.put("trimmer", this);
and finally in the velocity template do the following
$trimmer.trim("#render_something('xxx')")
Why does it work?
Although the behavior of Velocity is clearly define, it can be a bit tricky to see how it works sometimes. The separate trim()-method is necessary to get the char-sequence from the template into a Java method where you can call the actual trim() on the String. As far as I know there is no trim inside Velocity, but you always can call back to Java with tricks like this one.
The double-quotes are necessary because the #render_something is just a macro, not a function call, this means the results of the statements in the macro are put verbatim into the point where the macro is "executed".
I struggled a while to find a straightforward solution to whitespace gobbling, so here the one I finally came up with. It is inspired from and Vadzim's answer and this page http://wiki.apache.org/velocity/StructuredGlobbingResourceLoader
The StructuredGlobbingResourceLoader we can find on the website has a complex behaviour and doesn’t get rid of any kind of whitespace, so I modified it to get the simple behaviour: "Delete any whitespace at the beginning of the lines, and add a comment at the end of each line" (which prevents the linebreak evaluation). The filter is applied on the input stream at loading time.
This kind of velocity template
#if($value)
the value is $value
#end
is transformed to
#if($value)##
the value is $value##
#end##
Then if you want to have linebreaks or beginning of line whitespaces, you'll have to put($br,"\n") and put($sp," ") in your context like Vadzim's explained and explicitly use them in your template. This way of doing will allow you to keep indented templates, with maximum control.
take the class from this page http://wiki.apache.org/velocity/StructuredGlobbingResourceLoader
change the extended class to the kind of loader your need (this one uses the webapp loader)
replace the read() method with the code I provide
use the class as your resource loader in your properties. Example for the webapp loader: webapp.resource.loader.class=...StructuredGlobbingResourceLoader
public int read() throws IOException {
int ch;
switch(state){
case bol: //beginning of line, read until non-indentation character
while(true){
ch = in.read();
if (ch!=(int)' ' && ch!=(int)'\t'){
state = State.content;
return processChar(ch);
}
}
case content:
ch = in.read();
return processChar(ch);
//eol states replace all "\n" by "##\n"
case eol1:
state = State.eol2;
return (int)'#';
case eol2:
state = State.bol;
return (int)'\n';
case eof:
return -1;
}
return -1;
}
//Return the normal character if not end of file or \n
private int processChar(int ch){
switch(ch){
case -1:
state = State.eof;
return -1;
case (int)'\n':
state = State.eol1;
return (int)'#';
default:
return ch;
}
}
Any feedback on my implementation is welcome
Inspired by Velocity Whitespace Truncated By Line Comment one could use block comments instead of line comments for a better looking result:
#foreach( $record in $records )#**
*##if( $record.id == 0 )#**
*##end
#end
With a decent syntax highlighting the comments aren't very obtrusive.
Here is my alternative solution to velocity whitespace gobbling that allows tabbing template structure.
Each template text is preprocessed on first load in custom ResourceLoader:
private String enhanceTemplate(String body) {
if (!body.startsWith("##preserveWhitespace")) {
body = body.replaceAll("(##.*)?[ \\t\\r]*\\n+[ \\t\\r]*", Matcher.quoteReplacement("##\n"));
body = body.trim();
}
return body;
}
This replaces all new lines and adjustent spaces with just one commented newline.
Line breaks and tailing spaces can be inserted explicitly with $br and $sp variables from default context:
private static final VelocityContext DEFAULT_CONTEXT = new VelocityContext(new HashMap<String, String>() {{
put("sp", " ");
put("br", "\n");
}});
In some cases, I've had to essentially minimize my script like I would js or css. It works well, though it is not as easy for humans to read. Just one other option to eliminate the excess space:
<ul class="tabs">#foreach($par in $bodypars)#set( $parLen = ${_MathTool.toInteger($bodypars.size())} )#set( $parLn = $parLen - 1 )#set( $thClass = 'tb'+${parLn} )#set( $thaClass = '' )#if( $foreach.index == 1 )#set( $thClass = ${thClass}+' selected' )#set( $thaClass = ' selected' )#end#if($foreach.index != 0 && $parLen <= $maxTabs)#set ( $btitle = $_XPathTool.selectSingleNode($par,'item-subtitle') )<li class="${thClass}">#if($!btitle && $btitle != '')$_SerializerTool.serialize($btitle, true)#end</li>#end#end</ul>
You can use standard java trim, taking attention to your variable if are a object instead string.
$string.trim() //work fine
$object.trim() //exception
Have a good day!

Using a string containing variables in JOptionPane

I am trying to build a string using "if" statements, and then using the built string to show in a JOptionPane.
//If the value is zero, don't show the line item
if (intLays > 0)
strBuiltOrder = "intSnickers + \"Snickers\" + \"\\n\"";
In the end there would be one line item for each variable that had a value greater than zero. However, the problem is, when I use it in JOptionPane, it outputs the literal.
intSnickers + \"Snickers\" + \"\\n\"
Is there anyway I can build a string to insert into JOptionPane, or is there another way to withhold variables from the JOptionPane if their value is zero?
Is there a reason why you escape quotes and backslashes? The following probably does what you expect:
if (intLays > 0) {
strBuiltOrder = intSnickers + "Snickers\n";
}
If you want to build a more complex string you can look into StringBuilder or StringBuffer objects.
Along my own presumption, maybe you were looking for this:
//If the value is zero, don't show the line item
if (intLays > 0)
strBuiltOrder = intSnickers + "\"Snickers\"" + "\"\\n\"";
I hope this helps, or at least points you in the right direction, when I understand more about the expected output I can try to help you out further.
Instead of using a String, try using a StringBuilder then you won't have problems with the syntax of that statement. So your code might be something like:
StringBuilder sb = new StringBuilder(...);
...
if (intLays > 0)
sb.append(intSnickers).append("Snickers\n");
Strings are immutable, so it better to use something like the StringBuilder or StringBuffer.
The solution was:
if (intSnickers > 0)
BuiltOrder.append( intSnickers + "Snickers" + "\n");
This is meant to concatenate a string and insert it into a JOptionPane. I am still sort of confused about why it works this way, instead of the way I have it, but, oh well...

Categories