KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
We were asked to make a simple GUI calculator, and I used getSource() to detect the buttons, because that's what they taught us. It works by typing the first and second value and then choosing the operation. It worked. But I made a mistake, because they want us to make the numbers also be buttons, just like a real calculator. So how do I get the value of each button using getSource()? Like when I press button 1 and 2 is equal to 3. Here's what I've done: import java.awt.*; import java.awt.event.*; public class SimpleCalculator implements ActionListener { // Containers private Frame f; private Panel p1, p2, p3, p4; // Components private Label l1, l2, l3; private TextField tf1, tf2, tf3; private Button bAdd, bSub, bMul, bDiv, bClear; public SimpleCalculator() { f = new Frame("My First GUI App"); p1 = new Panel(); p2 = new Panel(); p3 = new Panel(); p4 = new Panel(); l1 = new Label("First: "); l2 = new Label("Second: "); l3 = new Label("Result: "); tf1 = new TextField(15); tf2 = new TextField(15); tf3 = new TextField(15); bAdd = new Button("+"); bSub = new Button("-"); bMul = new Button("*"); bDiv = new Button("/"); bClear = new Button("C"); } public void launchFrame() { // Use the default layout manager of the Panel (FlowLayout) p1.add(l1); p1.add(tf1); p2.add(l2); p2.add(tf2); p3.add(l3); p3.add(tf3); p4.add(bAdd); p4.add(bSub); p4.add(bMul); p4.add(bDiv); p4.add(bClear); // Change the layout manager of the Frame. // Use GridLayout(4, 1) f.setLayout(new GridLayout(4, 1)); f.add(p1); f.add(p2); f.add(p3); f.add(p4);
Tags (comma-separated)
Save Edits
Cancel