Home >Java >javaTutorial >How to Get the Value of a Button Click in an AWT Calculator?
How to Determine Button Value in AWT Calculator with getButton()
In your calculator implementation, you mentioned encountering an issue in obtaining the value of numerical buttons. This guide will address your question and provide a solution using the getSource() method in AWT.
Problem: You want to detect the source button that was clicked to determine the numerical value, since you've been using getSource() to identify other buttons.
Solution:
Code Example:
import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Calculator implements ActionListener { private Button[] numButtons; public Calculator() { // Initialize the numerical buttons numButtons = new Button[10]; } public void performCalculation(ActionEvent e) { Button sourceButton = (Button) e.getSource(); String value = sourceButton.getLabel(); // Process the numerical value obtained } // Override the actionPerformed method public void actionPerformed(ActionEvent e) { performCalculation(e); } // Main method public static void main(String[] args) { Calculator calculator = new Calculator(); // Logic to set up the GUI and register event listeners } }
By utilizing the getSource() method in this way, you can effectively determine which numerical button was clicked and retrieve its value. This enables you to perform the necessary calculations and display the results in your calculator application.
The above is the detailed content of How to Get the Value of a Button Click in an AWT Calculator?. For more information, please follow other related articles on the PHP Chinese website!