"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to use getSource() to get numeric button value in Java GUI calculator?

How to use getSource() to get numeric button value in Java GUI calculator?

Posted on 2025-04-29
Browse:438

How to Retrieve Number Button Values Using getSource() in a Java GUI Calculator?

How to Retrieve Button Values Using getSource()

In your GUI calculator, you've correctly used the getSource() method to detect button clicks. However, you're only capturing buttons for operations ( , -, *, /, C), but you need to handle number buttons as well.

To retrieve the value of each button, follow these steps:

  1. Create a separate action listener for the number buttons. In your code, you currently have one action listener that handles all buttons (bAdd, bSub, etc.). Create a separate action listener for the number buttons (e.g., numActionListener).
  2. Register the action listener for the number buttons. Add the numActionListener to all number buttons. For example:
b1.addActionListener(numActionListener);
b2.addActionListener(numActionListener);
b3.addActionListener(numActionListener);
// and so on...
  1. Override the actionPerformed method for the number buttons' action listener. In the actionPerformed method, you can retrieve the value of the specific number button that was clicked using the getSource() method.
@Override
public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    
    // Check if the source is a number button
    if (source instanceof Button) {
        Button button = (Button) source;

        // Get the value of the button
        String buttonValue = button.getLabel();

        // Append the value to the input text field (e.g., tf1)
        tf1.setText(tf1.getText()   buttonValue);
    }
    // ... (continue with your existing code to handle operation buttons)
}

By following these steps, you can retrieve the values of both the number and operation buttons when they are clicked. This will allow you to build a fully functional calculator that accepts user input for both numbers and operations.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3