import
java.awt.*;
import
javax.swing.*;
import
java.awt.event.*;
public
class
MyCalculator
extends
JFrame{
private
static
final
long
serialVersionUID = 1L;
private
String showStr=
"" ,remainStr= "" ,method= "" ;
private
boolean
isCalculated=
false ;
private
void
setShowStr(String showStr){
this .showStr=showStr;
}
private
String[] str={
"C" ,
"CE" ,
"+/-" ,
"7" ,
"8" ,
"9" ,
"4" ,
"5" ,
"6" ,
"1" ,
"2" ,
"3" , "0" ,
"." ,
"=" ,
"+" ,
"-" ,
"*" ,
"/" };
JButton[]
jbt= new
JButton[str.length];
JTextField
jtf= new
JTextField();
public
MyCalculator(){
for
(
int
i=
0 ;i<str.length;i++){
jbt[i]= new
JButton(str[i]);
}
JPanel
p1= new
JPanel();
p1.setLayout( new
GridLayout(
5 , 3 ));
for
(
int
i=
0 ;i<str.length- 4 ;i++){
p1.add(jbt[i]);
}
JPanel
p2= new
JPanel();
p2.setLayout( new
GridLayout(
4 , 1 ));
for
(
int
i=str.length-
4 ;i<str.length;i++){
p2.add(jbt[i]);
}
add(jtf,BorderLayout.NORTH);
add(p1,BorderLayout.CENTER);
add(p2,BorderLayout.EAST);
ButtonListener
listener= new
ButtonListener();
for
(
int
i=
0 ;i<str.length;i++){
jbt[i].addActionListener(listener);
}
}
class
ButtonListener
implements
ActionListener {
public
void
actionPerformed(ActionEvent e){
String
s=e.getActionCommand();
if
(s==
"C" &&showStr.length()> 0 ){
showStr=showStr.substring( 0 ,showStr.length()- 1 );
jtf.setText(showStr);
} //clear
else
if
(s==
"CE" ){
showStr= "" ;
remainStr= "" ;
isCalculated= false ;
jtf.setText(showStr);
}
//clear
all
else
if
(s==
"+" ||s== "-" ||s== "*" ||s== "/" ){
remainStr=showStr;
showStr= "" ;
method=s;
jtf.setText(showStr);
}
else
if
(s==
"+/-" &&showStr== "" ){
showStr+= "-" ;
jtf.setText(showStr);
}
else
if
(s==
"=" ){
jtf.setText(calculation(remainStr,showStr,method));
}
else
{
if (isCalculated){
showStr= "" ;
jtf.setText(showStr);
isCalculated= false ;
}
showStr+=s;
jtf.setText(showStr);
} //number
}
}
private
String calculation(String s1,String s2,String s3){
Double
num1=Double.parseDouble(s1);
Double
num2=Double.parseDouble(s2);
isCalculated= true ;
if
(s3==
"+" ){
setShowStr(num1+num2+ "" );
return
num1+num2+
"" ;
}
else
if
(s3==
"-" ){
setShowStr(num1-num2+ "" );
return
num1-num2+
"" ;
}
else
if
(s3==
"*" ){
setShowStr(num1*num2+ "" );
return
num1*num2+
"" ;
}
else
if
(s3==
"/" ){
setShowStr(num1/num2+ "" );
return
num1/num2+
"" ;
}
return
"error"
;
}
public
static
void
main(String[] args){
JFrame
frame= new
MyCalculator();
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
|