Home >Java >javaTutorial >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:
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.
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!