A Question about JTextField in Java - java

I met a small problem when running a Java class that I wrote, though the design is pretty straightforward. I've created a JPanel, and I've added four JTextFields onto it and I've attached a button to this JPanel, too. Then, I've associated an ActionListener to this button being pressed. The code is like:
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (imageIdField.getText() == "" &&
captionField.getText() == "" &&
creditField.getText() == "" &&
titleField.getText()== "")
{
mediaXML = "";
results.clear();
results.put("error1", "more");
}
else
{ ....
}
}
The strange thing is after I've pressed the OK button, and I did input text in those four JTextFields, still it will fall in the IF branch as if I didn't input any text in any of these four fields.
I've been debugging this for a while, but no clue. Could anyone give me some hint like whether .getText() == "" is a valid way for testing no input?
Thanks in advance!

As has been mentioned, using == is not correct. For readability, try:
field.getText().isEmpty()
or
field.getText().trim().isEmpty()

Generally a bad idea to use == on Strings, or most other things. It checks that the objects are exactly the same instance, not that they have the same value. "" != new String("").
field.getText().equals("")
Or possibly better:
field.getText().isEmpty()

Use getText().equals("") instead of ==

Use == to check if it is the same object in memory, and .equals("YOUR STRING") to check if the content of the object is the same.

You should use .equals. Also, you might want to do something like this:
imageField.getText().trim().length() == 0 //The same for the others
or
imageField.getText().trim().isEmpty() //The same for the others
if you want to make sure that the user has actually written some characters instead of just white spaces.

== only checks whether the left hand side and the right hand side refer to the exact same instance of an object. And since "" translates to something like new String(""), it will always return false, if you compare it with a string that already exists.
If you want to compare whether two instances of a class have the same state you need to use equals(). In your case *.getText().equals(""). A more elegant method would to use the isEmpty() method of the String class.

Related

JTextArea admin password control

Very new and inexperienced coder, I'm currently working on my first 'from - scratch' project which will be a simple POS (Point Of Sale) restaurant till application.
The till has an admin panel which allows the user to change the menu presets and prices and will require a password to access it.
I am sloppy and using a lot imports as I am as I said very new.
Please take a look at the following:
if (source == passwordSubmit){
if (logInPassword.getText() == adminPassword){
loginFrame.setVisible(false);
adminFrame.setVisible(true);
}
else logInPassword.append("Incorrect");
}
That code is within my ActionListener handler which lets the user enter text into the JTextArea called logInPassword and it compares the user text with the adminPassword preset string (currently set to Password as default)
But my code doesn't quite work... It's active as it gives me an "Incorrect" append into the logInPassword JTextArea but I'm typing in the correct password.
Do I need a getter or something?
Not sure what I'm missing.
use .equals()
if (source == passwordSubmit){
if (logInPassword.getText().equals(adminPassword){
loginFrame.setVisible(false);
adminFrame.setVisible(true);
}
else logInPassword.append("Incorrect");
}
When you use the == operator in Java, you are just comparing shallow reference values. The line source == passwordSubmit would work (since both should refer to the same object). However with strings, it is possible to have two string objects that equal the same in value. In that case, you have to do logInPassword.getText().equals(adminPassword) instead of logInPassword.getText() == adminPassword. The equals method compares by value of the strings.

Java KeyEvent confusion

I have a program which is a mock inventory system with quite a few JTextField's and some regular expressions which some of those fields must comply with. Also, some fields cannot be null(obviously) or an empty String. In order to assist the user to input data, I've added some ImageIcon's to show if the input data is valid or invalid. (a green check or red x) and I setVisibility() as the user types via KeyEvents.
With that said, here is the confusion. I have a block which I'm pretty sure doesn't have a bug in it, but I've found that there's some odd things happening:
I'm only calling my updateIcons() method in response to keyTyped() - my overrides for the others are empty. Now, when a key is typed, the text is printed on the screen before the key is released, so you would think that an input field that simply requires at least one character to NEVER fail the validity check because if keyTyped() is the only entry point to my updateIcons() method, there should always be at least one character by the time the key is released and thus registered as a "key typed". However, it seems to be firing an event before the key even gets registered to the System. Something which makes this even more odd is if I call my updateIcons() method twice in a row from the overridden keyTyped() method, the program STILL fails the check for empty string. BUT if I call it for keyPressed(), keyReleased(), and keyTyped() all for the same event, presto; valid data. Could this possibly be caused by the instability/bugginess of AWT?
Here is the updateIcons() method in case it is something I overlooked, but since I'm getting such odd results I don't think its a bug on my end.
//called from keyTyped
//formInputIcons is a 2D array[8][2] where the first dimension represents
//the form input field, and the second dimension is the ImageIcons for that field
//public final Pattern upcRegex = Pattern.compile("^\\d{12}$");
//public final Pattern anyNumRegex = Pattern.compile("^\\d+$");
public void updateIcons(KeyEvent e){
if(e.getSource() == formAddInputs[0]){
formInputIcons[0][0].setVisible( ! (upcRegex.matcher(
((JTextField)e.getSource()).getText()).matches()));
formInputIcons[0][1].setVisible(upcRegex.matcher(
((JTextField)e.getSource()).getText()).matches());
}else if(e.getSource() == formAddInputs[1]){
formInputIcons[1][0].setVisible(((JTextField)e.getSource()).getText().equals(""));
formInputIcons[1][1].setVisible( ! ((JTextField)e.getSource()).getText().equals(""));
}else if(e.getSource() == formAddInputs[3]){
formInputIcons[3][0].setVisible(((JTextField)e.getSource()).getText().equals(""));
formInputIcons[3][1].setVisible( ! ((JTextField)e.getSource()).getText().equals(""));
}else if(e.getSource() == formAddInputs[4]){
formInputIcons[4][0].setVisible(((JTextField)e.getSource()).getText().equals(""));
formInputIcons[4][1].setVisible( ! ((JTextField)e.getSource()).getText().equals(""));
}else if(e.getSource() == formAddInputs[6]){
formInputIcons[6][0].setVisible( ! (anyNumRegex.matcher(
((JTextField)e.getSource()).getText()).matches()));
formInputIcons[6][1].setVisible(anyNumRegex.matcher(
((JTextField)e.getSource()).getText()).matches());
}else if(e.getSource() == formAddInputs[7]){
formInputIcons[7][0].setVisible( ! (anyNumRegex.matcher(
((JTextField)e.getSource()).getText()).matches()));
formInputIcons[7][1].setVisible(anyNumRegex.matcher(
((JTextField)e.getSource()).getText()).matches());
}
}
UPDATE: I'm an idiot - it works fine if I only call updateIcons() once from keyReleased() and leave keyPressed() and keyTyped() empty. I like to learn things though; could someone explain why keyTyped() is buggy in this usage but keyReleased() works fine or post a link please?
You need to be calling your update method from keyReleased(). I've made a simple JTextField which outputs the key and its getText() each time a key is pressed, and watch what happens:
keyPressed:c
text:
keyTyped:c
text:
keyReleased:c
text:c
keyPressed:a
text:c
keyTyped:a
text:c
keyReleased:a
text:ca
keyPressed:t
text:ca
keyTyped:t
text:ca
keyReleased:t
text:cat
You can see that the actual text of the JTextField is not updated by the keyTyped() or keyPressed() events.

String tokenizer.nextToken() return value

When using an if statement, for instance,
if((isInt(search1.nextToken()) == true) && search1.nextToken() != "x")
would the result returned by search1.nextToken() have different values? This is all wrapped in a while loop as well, and I'm trying to figure out what would happen.
Yes, it would have different values. Whenever you do nextToken it would read the next available token. I would suggest to try with a simple java program to understand better.

how to make two textfield and one JCombobox have a condition just like in log-in's

i have two textfield and one JComboboxes the problem is i want the program to check if the textfields have "admins" typed in it and administrator selected in JCombobox if so the the program will show a messagebox to the user.
Your code in your comment:
if (btn1 == y.getSource() && tf1.toString() == "admin" &&
tf2.toString() == "admin" && c1.getSelectedIndex() == 0 )
shows you using == to compare Strings, and also trying to get text from a JTextField using toString(), neither of these is good. Instead for String comparison, use the equals(...) or equalsIgnoreCase(...) methods, not == since the latter checks to see if two objects are identical which is not what we're generally interested. We don't care if one String is held by a different object as another but rather that the two Strings have the same chars in the same order, which is what the two equals methods do.
Next, use the getText() method to extract the text held by your JTextField. For example:
if (btn1 == y.getSource() && tf1.getText().equals("admin") &&
tf2.getText().equals("admin") && c1.getSelectedIndex() == 0 )
Also, please show code as an edit to your question, not in a comment since it doesn't format well as a comment. Finally, if my advice doesn't help, consider showing us more code and giving more detailed information on the problem with this code.

Strings don't seem to be equal in Java on Android, even though they print the same

I've got a problem that I'm rather confused about. I have the following lines of code in my android application:
System.out.println(CurrentNode.getNodeName().toString());
if (CurrentNode.getNodeName().toString() == "start") {
System.out.println("Yes it does!");
} else {
System.out.println("No it doesnt");
}
When I look at the output of the first println statement it shows up in LogCat as "start" (without the quotes obviously). But then when the if statement executes it goes to the else statement and prints "No it doesn't".
I wondered if the name of the node might have some kind of non-printing character in it, so I've checked the length of the string coming from getNodeName() and it is 5 characters long, as you would expect.
Has anyone got any idea what's going on here?
Use String's equals method to compare Strings. The == operator will just compare object references.
if ( CurrentNode.getNodeName().toString().equals("start") ) {
...
Use CurrentNode.getNodeName().toString().equals("start").
In Java, one of the most common mistakes newcomers meet is using == to compare Strings. You have to remember, == compares the object identity (Think memory addresses), not the content.
You need to use .equals
if ("start".equals(CurrentNode.getNodeName().toString()) { ... }

Categories

Resources