Skip to content

Instantly share code, notes, and snippets.

@B-R-P
Last active February 21, 2023 14:23
Show Gist options
  • Save B-R-P/6b27e87ef1d77364f9742326c45aedf8 to your computer and use it in GitHub Desktop.
Save B-R-P/6b27e87ef1d77364f9742326c45aedf8 to your computer and use it in GitHub Desktop.
Calculator GUI in java
import javax.swing.*;
import java.awt.event.*;
import java.awt.GridLayout;
import java.util.*;
class CalculatorFrame extends JFrame implements ActionListener{
JTextField screen;
JPanel buttonPanel;
String operation;
Integer result;
List<String> operations = Arrays.asList("+","-","*","/","%","C","=");
CalculatorFrame(){
screen = new JTextField();
screen.setBounds(10, 10, 200, 30);
add(screen);
buttonPanel = new JPanel(new GridLayout(5,4));
buttonPanel.setBounds(10,50,200,125);
for (int i=0; i<=9; i++) addButton(""+i);
for (String op : operations) addButton(op);
add(buttonPanel);
}
void addButton(String txt){
JButton btn = new JButton(txt);
btn.addActionListener(this);
buttonPanel.add(btn);
}
void doAction(String op){
if(op=="C"){
screen.setText("");
operation=null;
result = 0;
return;
}
String screenText = screen.getText();
if(screenText.length()==0) return;
Integer operand = Integer.parseInt(screenText);
if(operation!=null){
switch(operation){
case "+": result += operand; break;
case "-": result -= operand; break;
case "*": result *= operand; break;
case "/":
try{
result/=operand;
}catch(ArithmeticException e){
screen.setText(e.getMessage());
return;
}
break;
case "%":
try{
result%=operand;
}catch(ArithmeticException e){
screen.setText(e.getMessage());
return;
}
break;
}
}else
result=operand;
if(op=="="){
screen.setText(result.toString());
operation=null;
}else{
screen.setText("");
operation=op;
}
}
public void actionPerformed(ActionEvent e){
String sourceText = ((JButton)e.getSource()).getText();
if(operations.contains(sourceText))
doAction(sourceText);
else
screen.setText(screen.getText()+sourceText);
}
}
class calculator{
public static void main(String[] args) {
CalculatorFrame frame = new CalculatorFrame();
frame.setTitle("Calculator");
frame.setLayout(null);
frame.setSize(235, 225);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
@B-R-P
Copy link
Author

B-R-P commented Feb 21, 2023

calculator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment