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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-28 10:06:16719browse

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.

The above is the detailed content of How to Retrieve Number Button Values Using getSource() in a Java GUI Calculator?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn