Java help for newb

WdnUlik2no

Member
May 5, 2005
169
0
0
Hello,

I need a little help in java namely regarding the JTextField. Is there anyway to get the text from the field and compare it to another string? No matter what I do the result is always false. I even initialized the value of the JTextField to "", but when I compare it to a string that also equals "", the result is still false. Please see example:

import java.awt.event.*;
import javax.swing.*;

public class CListener implements ActionListener
{
private JTextField textField;
boolean dec = false;
boolean first = false;
private String op;
double num1, num2, result;

//Constructor
public CListener(JTextField t)
{
textField = t;
textField.setText("");
System.out.println(textField.equals(""));
op = "";
num1 = num2 = result = 0.0;
}

}

Output after I create new CListener:

C:\JAVAFI~2\Chapter13>java CListener
false
C:\JAVAFI~2\Chapter13>

Why isn't this value true if textField.getText() = ""? Please help.
 

Thyme

Platinum Member
Nov 30, 2000
2,330
0
0
Use getText()

You're comparing a String to a JTextField and which is comparable as Object to Object. Such comparisons are based on the address which of course will always be different.
 

WdnUlik2no

Member
May 5, 2005
169
0
0
public CalculatorListener(JTextField t)
{
textField = t;
textField.setText("");
System.out.println(textField.getText() == "");
op = "";
num1 = num2 = result = 0.0;
}


OK, I tried this on line 5:

textField.getText() == "";

and I still get the same result:
false
 

Thyme

Platinum Member
Nov 30, 2000
2,330
0
0
println(textField.getText());
println(op);

And see if that aids in debugging.
 

Kilrsat

Golden Member
Jul 16, 2001
1,072
0
0
You need to use .equals comparisons for strings.

So:

textField.getText().equals("") is the check you want, not textField.getText() == ""
 

SinNisTeR

Diamond Member
Jan 3, 2001
3,570
0
0
Originally posted by: Kilrsat
You need to use .equals comparisons for strings.

So:

textField.getText().equals("") is the check you want, not textField.getText() == ""

winnar