import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CalculatorTest2 extends JFrame implements ActionListener
{
JTextField tf;
JPanel p;
JButton[] button;
String str_num;
String temp1, temp2;
double result;
boolean check_point;
public CalculatorTest2()
{
this.setSize(300, 250);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tf = new JTextField("0");
tf.setHorizontalAlignment(JTextField.RIGHT);
add(tf, "North");
p = new JPanel(new GridLayout(5, 4, 5, 5));
String str_button[] = {
"←", "CE", "C", "+",
"7", "8", "9" , "/",
"4", "5", "6" , "*",
"1", "2", "3" , "-",
"0", ".", "=" };
button = new JButton[str_button.length];
for(int i=0; i<str_button.length; i++)
{
button[i] = new JButton(str_button[i]);
button[i].addActionListener(this);
p.add(button[i]);
}
this.add(p);
}
public void actionPerformed(ActionEvent e)
{
String source = e.getActionCommand();
str_num = tf.getText();
if(source == "C")
{
tf.setText("0");
temp1=temp2 ="";
}
if(source == "CE")
{
tf.setText("0");
}
if(source == "←")
{
String temp = null;
if(!str_num.equals("0"))
{
try
{
temp = tf.getText();
tf.setText(temp.substring(0, temp.length()-1));
}
catch(StringIndexOutOfBoundsException se)
{
tf.setText("0");
}
}
}
if(source=="+" || source=="-" || source=="*" || source=="/")
{
tf.setText(""+result);
temp1 = str_num;
temp2 = source;
tf.setText("0");
}
if(source == "=")
{
if(temp2=="+")
result = Double.parseDouble(temp1)+Double.parseDouble(str_num);
if(temp2=="-")
result = Double.parseDouble(temp1)-Double.parseDouble(str_num);
if(temp2=="*")
result = Double.parseDouble(temp1)*Double.parseDouble(str_num);
if(temp2=="/")
result = Double.parseDouble(temp1)/Double.parseDouble(str_num);
tf.setText(""+result);
}
if(source=="0" || source=="1" || source == "2" || source == "3"
|| source == "4" || source == "5" || source == "6"
|| source == "7" || source == "8" || source == "9")
{
if(str_num.equals("0"))
tf.setText(source);
else
tf.setText(str_num+source);
}
if(source=="." && check_point)
{
tf.setText(str_num+source);
check_point = false;
}
}
public static void main(String[] args)
{
new CalculatorTest2();
}
}
댓글 없음:
댓글 쓰기