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:
b1.addActionListener(numActionListener); b2.addActionListener(numActionListener); b3.addActionListener(numActionListener); // and so on...
@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.
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