When i compare the getText function of a JTextField with an equal String, it doesn´t return true

58 Views Asked by At

So i have this calculator (on Java) and when i press a button i wanna check if in the JTextField(pantalla) is only "0" so i can replace it with the number instead of concatenate the button i pressed... the thing i´ve noticed is that when i try it, it returns false everytime

i´ve tried to save the .getText() into a String variable and then compare it to the literal "0", i even try to put the text to "0" 1 line above the comparation with the .setText().

pantalla = new JTextField();
pantalla.setHorizontalAlignment(SwingConstants.RIGHT);
pantalla.setBounds(72, 19, 144, 25);
contentPane.add(pantalla);
pantalla.setColumns(10);
pantalla.setText("0");
        
JButton btn0 = new JButton("0");
btn0.addActionListener(new ActionListener() 
{
    public void actionPerformed(ActionEvent e) 
    {
    pantalla.setText("0");
    System.out.println(pantalla.getText() == "0");
//  pantalla.setText(pantalla.getText() + btn0.getText());
    }
});

heres the output of the code ive just shown: image(https://i.stack.imgur.com/g62Sp.png)

1

There are 1 best solutions below

0
Andrej Istomin On BEST ANSWER

When you compare a content of the strings, you should use equals() instead of == (that compares the objects' references). Read more here and here

So, change your code:

System.out.println(pantalla.getText() == "0");

to

System.out.println("0".equals(pantalla.getText()));

and you will get the desired result.