import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class calculator extends JFrame implements ActionListener {
JTextField t1 = new JTextField(20);
String oper = "";
int first = 0, second = 0, result = 0;
public calculator() {
String[] buttons = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", "=", "+", "%"};
JPanel panel = new JPanel(new GridLayout(4, 4));
for (String text : buttons) {
JButton button = new JButton(text);
button.addActionListener(this);
panel.add(button);
}
JButton space = new JButton("C");
space.addActionListener(this);
setLayout(new BorderLayout());
add(t1, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
add(space, BorderLayout.SOUTH);
setTitle("Calculator");
setSize(250, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae) {
String a = ae.getActionCommand();
if ("0123456789".contains(a)) {
t1.setText(t1.getText() + a);
} else if ("+-*/%".contains(a)) {
first = Integer.parseInt(t1.getText());
oper = a;
t1.setText("");
} else if (a.equals("=")) {
second = Integer.parseInt(t1.getText());
switch (oper) {
case "+": result = first + second; break;
case "-": result = first - second; break;
case "*": result = first * second; break;
case "/": result = first / second; break;
case "%": result = first % second; break;
}
t1.setText(String.valueOf(result));
} else if (a.equals("C")) {
t1.setText("");
}
}
public static void main(String[] args) {
new calculator();
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: