Search code examples
javajbuttonactionlistenerjlabelsettext

Changing label text using ActionListener


I'm trying to make a program that allows me to change the text of a label when clicking different buttons, however regardless of what button I click the text of the label changes to the 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 is " + sum, "Answer", JOptionPane.PLAIN_MESSAGE);
        }       
    }
}

Solution

  • Your problem is that you are not including the label.setText() method inside your if statements. Because of this it will execute every label.setText() call and keep overriding the text until it defaults to the final call in your method. It is better to use braces, even for one line if statements, to avoid this problem.

     if(e.getSource() == add) {
        operator = "+";
        label.setText("+");
    }
    

    Also, since only one of the conditions is going to be true, you can use an else if.