java - How to change a JTextField based on a JComboBox selection -
this silly program working on school having trouble. have jcombobox , based on user selects want change text field. i'm having trouble however, stands program compiles , runs text field doesn't change. i've found plenty of examples of people doing far more complicated things need simple solution. here code. thanks!
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class emocon extends jframe implements itemlistener { jpanel row1 = new jpanel(); jcombobox choose = new jcombobox(); jpanel row2 = new jpanel(); jtextfield text = new jtextfield(10); //image displayed here jpanel row3 = new jpanel(); jlabel pic = new jlabel(); //images imageicon happy = new imageicon("images/happy.gif"); imageicon lol = new imageicon("images/lol.gif"); imageicon winky = new imageicon("images/winky.gif"); imageicon sad = new imageicon("images/sad.gif"); imageicon worried = new imageicon("images/worried.gif"); imageicon angry = new imageicon("images/angry.gif"); imageicon shock = new imageicon("images/shock.gif"); imageicon uninpressed = new imageicon("images/uninpressed.gif"); imageicon yawn = new imageicon("images/yawn.gif"); imageicon evil = new imageicon("images/evil.gif"); public emocon(){ settitle("emoticon converter"); setsize(350,350); setdefaultcloseoperation(jframe.exit_on_close); setvisible(true); gridlayout 2 = new gridlayout(3,1); setlayout(two); choose.additem("happy"); choose.additem("lol"); choose.additem("winky"); choose.additem("sad"); choose.additem("worried"); choose.additem("angry"); choose.additem("shock"); choose.additem("uninpressed"); choose.additem("yawn"); choose.additem("evil"); choose.additemlistener(this); row1.add(choose); row2.add(text); row3.add(pic); add(row1); add(row2); add(row3); } @override public void itemstatechanged(itemevent item) { object source = item.getsource(); string emo = source.tostring(); if (emo == "sad"){ text.settext("hjgjhg"); } } public static void main(string[] args) { emocon emo = new emocon(); } }
you've problem here:
if (emo == "sad"){ text.settext("hjgjhg"); }
don't compare strings using ==
. use equals(...)
or equalsignorecase(...)
method instead. understand == checks if 2 objects same not you're interested in. methods on other hand check if 2 strings have same characters in same order, , that's matters here. instead of
if (fu == "bar") { // }
do,
if ("bar".equals(fu)) { // }
or,
if ("bar".equalsignorecase(fu)) { // }
edit
your other problem you're getting source itemevent. source jcombobox, not want. need selected item!
try using different method available in itemevent object, not getsource()
.
Comments
Post a Comment