我有一个小的计算器只能计算加减乘除
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class A extends JFrame implements ActionListener , ItemListener
{
private JComboBox list;
private TextField t1 , t2 , t3;
private JButton b1,b2;
private String s = "+";
Label l = new Label("Double中不会抛异常为什么还要让我们写一个分母不能为零的异常!");
A()
{
//创建三个文本框对象
t1 = new TextField(6);
t2 = new TextField(6);
t3 = new TextField(6);
//创建一个JButton " = "按钮
b1 = new JButton(" = ");
//创建下拉列表list
list = new JComboBox();
//在下拉列表中添加运算符号
list.addItem("+");
list.addItem("-");
list.addItem("*");
list.addItem("/");
//设置当前容器的的位置
this.setBounds(150,200,800,300);
//设置当前容器的布局方式
this.setLayout(new FlowLayout());
//向容器中添加t1 list t2 b2 t3
this.add(t1);
this.add(list);
this.add(t2);
this.add(b1);
this.add(t3);
this.add(l);
//创建监听按钮
list.addItemListener(this);
b1.addActionListener(this);
//设置当前容器是否可见
this.setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
/*if(list.getSelectedIndex() == 0)//getSelectedIndex()返回列表中与给定项匹配的第一个选项。
s = "+";
else*/
s = list.getSelectedItem().toString();//getSelectedItem() 返回当前所选项。
}
public void actionPerformed(ActionEvent e)
{
if("+" == s && t1.getText().length() != 0 && !t2.getText().equals(""))
{
try
{
Double d1 = new Double(t1.getText());
Double d2 = new Double(t2.getText());
Double d = d1 + d2;
t3.setText(d.toString());
}
catch(Exception e1)
{
System.out.println("运算中不能为非数字类型");
}
}
else
{
if("-" == s && t1.getText().length() != 0 && !t2.getText().equals(""))
{
try
{
Double d1 = new Double(t1.getText());
Double d2 = new Double(t2.getText());
Double d = d1 - d2;
t3.setText(d.toString());
}
catch(Exception e2)
{
System.out.println("运算中不能为非数字类型");
}
}
else
{
if("*" == s && t1.getText().length() != 0 && !t2.getText().equals(""))
{
try
{
Double d1 = new Double(t1.getText());
Double d2 = new Double(t2.getText());
Double d = d1 * d2;
t3.setText(d.toString());
}
catch(Exception e3)
{
System.out.println("运算中不能为非数字类型");
}
}
else
{
if("/" == s && t1.getText().length() != 0 && !t2.getText().equals(""))
{
try
{
Double d1 = new Double(t1.getText());
Double d2 = new Double(t2.getText());
//try
//{
Double d = d1 / d2;
t3.setText(d.toString());
//}
//catch(Exception ee)
//{
// System.out.println("被除数不能为零!!!");
//}
}
catch(Exception e4)
{
System.out.println("运算中不能为非数字类型");
}
}
}
}
}
}
}
public class Test12_2
{
public static void main(String[] zdw)throws Exception
{
new A();
}
}