Reputation:
I'm creating a user name confirm box, and I need to confirm if the text typed into the text field matches with the already defined type in a variable name
.
I don't know how to get it. I had been trying by implementing the following code, which in the action performed once the button is pressed it will verify if the textfield matches with the variable name.
code is as follows.
public class Action extends JFrame implements ActionListener
{
JLabel l;
JTextField t;
JButton b;
final String name = "harry";
public Action()
{
l = new JLabel("Name");
l.setBounds(10, 10, 100, 33);
t = new JTextField();
t.setBounds(60, 10, 100, 30);
b = new JButton("send text");
b.setBounds(80, 120, 100, 40);
add(l);
add(t);
add(b);
setSize(300, 300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e)
{
if (t.getText() == name)
{
JOptionPane.showMessageDialog(this, "you mach");
}
else
{
JOptionPane.showMessageDialog(this, "you dont");
}
}
public static void main(String[] args)
{
new Action();
}
}
Upvotes: 0
Views: 77
Reputation: 1037
In your Action()
constructor, you have to add an actionlistener to the frame:
addActionListener(this);
in order for it to work;
Also, you compare strings by .equals()
because strings are objects. Stack does not store the string's value, the heap does. To compare the string's value, you have to call t.getText().equals(name)
Change that in your actionPerformed()
class and you are good to go!
Upvotes: 2