Search code examples
javaswingbuttonjframeactionlistener

single actionlistener for multiple buttons


Can anyone help me out how to add single action listener on multiple buttons? Here is my code of multiple action listener for multiple buttons. I have also tried taking one common button for an action listener for all buttons. Can anyone please suggest me a relevant answer. I am a beginner and I don't have much knowledge in java.

import java.awt.event.ActionListener;
import javax.swing.*;

public class Calculator {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        JFrame frame = new JFrame();     //object of JFrame
        JLabel firstValue, secondValue, result, answer;     //declaration of JLabel
        JTextField one, two;     //declaration of JTextField
        JButton addition, subtraction, multiplication, division;     //declaration of JButton

        //Label for first value
        firstValue = new JLabel("First Value:");
        firstValue.setBounds(50,70,100,30);
        frame.add(firstValue);      

        //Label for second value
        secondValue = new JLabel("Second Value:");
        secondValue.setBounds(50,120,100,30);
        frame.add(secondValue);     

        //TextFields for first value    
        one = new JTextField();
        one.setBounds(170, 70, 105, 30);
        frame.add(one);

        //TextFields for second value
        two = new JTextField();
        two.setBounds(170, 120, 105, 30);
        frame.add(two);

        //Button for addition
        addition = new JButton("+");
        addition.setBounds(50, 170, 45, 30);
        frame.add(addition);

        //Button for subtraction
        subtraction = new JButton("-");
        subtraction.setBounds(110, 170, 45, 30);
        frame.add(subtraction);

        //Button for multiplication
        multiplication = new JButton("*");
        multiplication.setBounds(170, 170, 45, 30);
        frame.add(multiplication);

        //Button for division
        division = new JButton("/");
        division.setBounds(230, 170, 45, 30);
        frame.add(division);

        //Label for Result
        result = new JLabel("Result");
        result.setBounds(50, 220, 100, 30);
        frame.add(result);

        //TextFields for first value    
        answer = new JLabel();
        answer.setBounds(170, 220, 105, 30);
        frame.add(answer);

        //actionListener for addition button
        addition.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                //logic for addition
                int finalAnswer = Integer.parseInt(one.getText()) + Integer.parseInt(two.getText());
                answer.setText(Integer.toString(finalAnswer));

            }
        });


        //actionListener for subtraction button
        subtraction.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                //logic for addition
                int finalAnswer = Integer.parseInt(one.getText()) - Integer.parseInt(two.getText());
                answer.setText(Integer.toString(finalAnswer));              
            }
        });

        //actionListener for multiplication button
        multiplication.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                //logic for addition
                int finalAnswer = Integer.parseInt(one.getText()) * Integer.parseInt(two.getText());
                answer.setText(Integer.toString(finalAnswer));              
            }
        });     

        //actionListener for division button
        division.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                //logic for addition
                int finalAnswer = Integer.parseInt(one.getText()) / Integer.parseInt(two.getText());
                answer.setText(Integer.toString(finalAnswer));              
            }
        });     

        frame.setSize(400,400);     //set size of JFrame with width and height
        frame.setLayout(null);      //set layout type by null
        frame.setVisible(true);     //set JFrame visible by boolean value true/false    
    }
}

Solution

  • Generally, you would do something like this (you could append this within your Calculator class):

    class Calculator {
    
      private JButton subtraction;
    
      public static void main(String[] args) {
        // your code
    
        // button example
        subtraction = new JButton("-");
        subtraction.addActionListener(new Listener());
    
        // your code
      }
    
      class Listener implements ActionListener {
    
        @Override
        public void actionPerformed(ActionEvent e) {
          if (e.getSource() == nameOfJButton) {
            // do the action for this button
          } else if (e.getSource() == nameOfAnotherButton) {
            // you get the idea
          }
        }
    
      }
    
    }
    

    And now, you can alter your code like so:

    // actionListener for addition button
    addition.addActionListener(new Listener());