java - Error with an If Statement within a GUI (Always falls into ELSE never IF) -
this question has answer here:
- how compare strings in java? 23 answers
i'm making basic login prompt gui revision java exam next week (this exercise possibly come in exam that's why i'm trying ace first). when type in name, in case 'joe' it'll verified, otherwise it'll unverified. however, when type in joe it'll still unverified. can see i've gone wrong? thanks.
package gui.eventhandler; import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.joptionpane; import javax.swing.jpanel; import javax.swing.jtextfield; public class eventhandlerexample2_nameconfirmation { private jframe frame; private jpanel panel; private jbutton button1; private jlabel label; private jtextfield fname; public eventhandlerexample2_nameconfirmation() { frame = new jframe("log in"); panel = new jpanel(); label = new jlabel("first name: "); fname = new jtextfield(20); // actions when ok button clicked // implementing actionlistener anonymous inner class button1 = new jbutton("submit"); button1.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { string inputname = fname.gettext(); if (inputname == "joe") { joptionpane.showmessagedialog(null, "verified user " + inputname); } else { //selects option regardless of entry joptionpane.showmessagedialog(null, "invalid user " + inputname); } } }); panel.add(label); // add label panel.add(fname); // textfield panel.add(button1); // , button panel frame.add(panel); // add panel onto frame frame.setvisible(true); // default invisible frame.setsize(600, 70); // 600 width 70 height frame.setlocation(350, 350); // center screen frame.setdefaultcloseoperation(jframe.exit_on_close); // exit when closed } public static void main(string[] args) { eventhandlerexample2_nameconfirmation app = new eventhandlerexample2_nameconfirmation(); } }
use string.equals compare strings operator == checks if references string equal
Comments
Post a Comment