java - Changing label text using ActionListener -


i'm trying make program allows me change text of label when clicking different buttons, regardless of button click text of label changes last line of actionperformed.

import java.awt.*; import java.awt.event.*;  import javax.swing.*;  public class gui extends jframe{ private jbutton add; private jbutton subtract; private jbutton multiply; private jbutton divide; private jtextfield box1; private jtextfield box2; private jlabel label; private jbutton ansbutton; public string operator;   public gui(){     super("luke's calculator");     setlayout(new flowlayout());     add = new jbutton("add");     subtract = new jbutton("subtract");     multiply = new jbutton("multiply");     divide = new jbutton("divide");     add(add);     add(subtract);     add(multiply);     add(divide);     box1 = new jtextfield(10);     label = new jlabel();     box2 = new jtextfield(10);     ansbutton = new jbutton("answer");     add(box1);     add(label);     add(box2);     add(ansbutton);      handlerclass handler = new handlerclass();     add.addactionlistener(handler);     subtract.addactionlistener(handler);     multiply.addactionlistener(handler);     divide.addactionlistener(handler);     ansbutton.addactionlistener(handler); } public class handlerclass implements actionlistener{     public double sum;     public double fn;     public double sn;      public void actionperformed(actionevent e) {         if(add.isselected())             operator = "+";         label.settext("+");          if(subtract.isselected())             operator = "-";         label.settext("-");          if(multiply.isselected())             operator = "x";         label.settext("x");          if(divide.isselected())             operator = "/";         label.settext("/");          if(ansbutton.isselected())             joptionpane.showmessagedialog(null, "the answer " + sum, "answer", joptionpane.plain_message);         }            } } 

your problem not including label.settext() method inside if statements. because of execute every label.settext() call , keep overriding text until defaults final call in method. better use braces, 1 line if statements, avoid problem.

 if(e.getsource() == add) {     operator = "+";     label.settext("+"); } 

also, since 1 of conditions going true, can use else if.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -