I need help figuring this out in java. All I have so far is the buttons for numb
ID: 3833806 • Letter: I
Question
I need help figuring this out in java. All I have so far is the buttons for numbers 0-9. I'm not sure how to add, subtract, or basically get them to do anything besides show up on the frame. Anytime I try to add any functionality to the buttons, the whole thing just falls apart and results in errors all over. Please help, or at least guide me in the right direction, I'd really appreciate it!
The original problem:
Create a GUI Calculator with the standard functionality of addition, subtraction, multiplication and division. You calculator should also have the additional functionality of sine, cosine, tangent, square, cube, raise to x to the power of y, and square root.
Your calculator should also have a memory button, memory recall button, and clear. The calculation should be displayed in a text field or text area based on your design.
Explanation / Answer
Just like you added button for numbers 1-9 you can also do the same for other buttons of the calculator like +,-,/,*,= etc... and arrange then properly on the frame.
Once you have UI ready the next task is to add functionality to the UI components in this they are buttons and a textbox. The functionality of the button is to tell what happens when the button is clicked. For example when a number is press the corresponding number on the button should be appended to the calculator textbox. For that there are something call event listeners. EventListeners register to an event of a component and they contain the functionality to be executed when the particular event is fired.
All you have to do is to register a lister to the buttons and provide the functionality as follows:
For a button, you can register an action event using addActionListener method which takes in object of ActionListener as a parameter. ActionListener is an interface and it has a method actionPerformed which gets called automatically whenever there is an action i.e, click is performed on the button. You can do it as follows: (say the names for digit buttons are digitBtn1, digitBtn2... and name of the text box is txtBox)
digitButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// append the digit to the textbox of the calculator
txtBox.setText(txtBox.getText() + digitButton1.getText());
}
});
You will write the same code for all the buttons. Only thing that changes is the code inside the actionPerformed method. In general the code is
digitButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// functionality to be executed when the action is performed.
}
});
For buttons like =, sine, square etc you will write the corresponding functionality inside that method. I hope that helps :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.