Last active
January 6, 2024 05:20
-
-
Save L8RFN/dbe86b08af0886ae5f2517d76cd52a38 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.swing.*; | |
import java.awt.*; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
public class GUI extends JFrame implements ActionListener { | |
JButton numbers [] = new JButton[12]; | |
JTextField up; | |
JPanel num; | |
int sum; | |
public GUI(){ | |
num= new JPanel(); | |
num.setLayout(new GridLayout(4,3)); | |
//initialize buttons | |
numbers[9]= new JButton("+"); | |
numbers[10]= new JButton("="); | |
numbers[11]= new JButton("C"); | |
for (int i = 0; i < numbers.length; i++) { | |
if (i<9) | |
numbers[i]=new JButton(i+1+""); | |
num.add(numbers[i]); | |
numbers[i].addActionListener(this); | |
} | |
up = new JTextField(); | |
add(up,BorderLayout.NORTH); | |
add(num); | |
setVisible(true); | |
setSize(300,400); | |
setTitle("Kids Calculator"); | |
setDefaultCloseOperation(EXIT_ON_CLOSE); | |
setLocationRelativeTo(null); | |
} | |
public void actionPerformed (ActionEvent ae){ | |
JButton clicked = (JButton) ae.getSource(); | |
if (!clicked.getText().equals("=")&& !clicked.getText().equals("C")) { | |
up.setText(up.getText() + clicked.getText());//concatenate | |
if (!clicked.getText().equals("+")){ | |
sum+=Integer.parseInt(clicked.getText()); | |
} | |
} | |
else if (clicked.getText().equals("C")) | |
{ | |
sum=0; | |
up.setText(""); | |
} | |
else | |
up.setText(sum+""); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment