public class Calculator extends JFrame{
private JPanel panel;
private JTextField display;
private JButton[] button;
static String lastCommand = null;
double res;
int tmp=0;
boolean bool=false;
private final String[] btn = {"1","2","3","4","5","6","7","8","9","0","C","+","-","*","/","="};
public Calculator() {
GridLayout gridLayout = new GridLayout(4,4,5,5);
panel = new JPanel(gridLayout);
display = new JTextField("0");
display.setFont(new Font("Arial",Font.BOLD,40));
display.setHorizontalAlignment(JTextField.RIGHT);
display.setEditable(false);
add(display,BorderLayout.NORTH);
add(panel, BorderLayout.SOUTH);
button = new JButton[16];
HandlerClass handler = new HandlerClass();
for(int i=0;i<btn.length;i++)
{
button[i] = new JButton(btn[i]);
button[i].setForeground(Color.red);
button[i].setFont(new Font("Arial",Font.BOLD,30));
panel.add(button[i]);
button[i].addActionListener(handler);
}
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent e) {
String clickBtn = e.getActionCommand();
if(clickBtn.equalsIgnoreCase("C"))
{
display.setText("0");
}
else if(clickBtn.equals("+"))
{
lastCommand="+";
tmp = Integer.parseInt(display.getText());
bool = true;
}
else if(clickBtn.equals("-"))
{
lastCommand="-";
tmp = Integer.parseInt(display.getText());
bool = true;
}
else if(clickBtn.equals("*"))
{
lastCommand="*";
tmp = Integer.parseInt(display.getText());
bool = true;
}
else if(clickBtn.equals("/"))
{
lastCommand="/";
tmp = Integer.parseInt(display.getText());
display.setText("0");
}
else if (clickBtn.equalsIgnoreCase("="))
{
double num2 = Integer.parseInt(display.getText());
if(lastCommand.equals("+"))
{
display.setText(String.valueOf(num2+tmp));
res=num2+tmp;
}
else if(lastCommand.equals("-"))
{
display.setText(String.valueOf(tmp-num2));
res=tmp-num2;
}
else if(lastCommand.equals("*"))
{
display.setText(String.valueOf(num2*tmp));
res=num2*tmp;
}
else if(lastCommand.equals("/"))
{
try{
display.setText(String.valueOf(tmp/num2));
if(num2 == 0)
{
display.setText("Error");
}
res=tmp/num2;
}catch(ArithmeticException x)
{
display.setText("");
}
}
}
else
{
if(display.getText().equals("0") || bool==true)
{
display.setText("");
bool = false;
}
display.setText(display.getText()+e.getActionCommand());
}
}
}
}