package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test08{
@SuppressWarnings("deprecation")
public static void main(String[]args){
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e){}
JFrame frame=new CalculatorFrame();
frame.show();
}
}
class CalculatorPanel extends JPanel implements ActionListener{
private JTextField display;
private JButton btn;
private double arg=0;
private String op="=";
private boolean start=true;
public CalculatorPanel(){
setLayout(new BorderLayout());
display=new JTextField("0");
display.setEditable(false);
add(display,"North");
JPanel p=new JPanel();
p.setLayout(new GridLayout(4,4));
String buttons="789/456*123-0.=+";
for(int i=0;i<buttons.length();i++){
btn=new JButton(buttons.substring(i,i+1));
p.add(btn);
btn.addActionListener(this);
}
add(p,"Center");
}
public void actionPerformed(ActionEvent evt){
String s=evt.getActionCommand();
if('0'<=s.charAt(0)&&s.charAt(0)<='9'|| s.equals(".")){
if(start)display.setText(s);
else display.setText(display.getText()+s);
start=false;
}
else{
if(start){
if(s.equals("-")){
display.setText(s);
start=false;
}
else op=s;
}
else{
double x=Double.parseDouble(display.getText());
calculate(x);
op=s;
start=true;
}
}
}
public void calculate(double n){
if(op.equals("+"))arg+=n;
else if(op.equals("-"))arg-=n;
else if(op.equals("*"))arg*=n;
else if(op.equals("/"))arg/=n;
else if(op.equals("="))arg=n;
display.setText(""+arg);
}
}
class CalculatorFrame extends JFrame{
public CalculatorFrame(){
setTitle("java2");
setSize(220,180);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Container contentPane=getContentPane();
contentPane.add(new CalculatorPanel());
}
}