实验11,图形界面2

 

 

class counter extends JFrame
{
public counter()
{
super("计算器");
this.setSize(400,100);
this.setLocation(300,240);
this.setLayout(new FlowLayout()); //确定窗口格式为流输入
TextField text1=new TextField(4);
text1.setText("1");
this.add(text1);

String proList[] = { "+","-","x" ,"%"}; //将"+","-","x" ,"%"作为列表元素
TextField text;
JComboBox comboBox; //创建下拉复选框
Container conPane = getContentPane(); //创建一个名为conPane的容器
comboBox = new JComboBox(proList); //把列表元素加入下拉复选框
comboBox.setEditable(true); //使复选框变为可操作
conPane.add(comboBox); //将复选框加入容器中

TextField text2=new TextField(4);
text2.setText("1");
this.add(text2);
JButton button = new JButton("=");
this.add(button);
TextField text3=new TextField(4);
text3.setText("2");


button.addActionListener(new ActionListener(){ //添加按钮监听事件
public void actionPerformed(ActionEvent e) //创建事件响应函数
{
String s=comboBox.getEditor().getItem().toString(); //获取复选框中的元素
double a= Integer.parseInt(text1.getText()); //将两个文本框中的字符串强制转换成浮点型,以便于之后的计算
double b= Integer.parseInt(text2.getText());
if(s.equals("+")) { //判断复选框中的元素种类
double t=a+b;
String m=String.valueOf(t); //由于文本框中的数据流只能为字符串,这里就需要将计算得到的浮点型数据强制转换成字符串型

text3.setText(m); //将最后的结果放在文本框中
}
else if(s.equals("-")) //后面的与之前的类似,不在注释
{double t=a-b;
String m=String.valueOf(t);

text3.setText(m);}
else if(s.equals("x"))
{double t=a*b;
String m=String.valueOf(t);

text3.setText(m);}
else
{double t=a/b;
String m=String.valueOf(t);

text3.setText(m);}

}});
conPane.add(text3);
this.setVisible(true); //将窗口设置为可视化
}



}

public class Counter {
public static void main(String[] args)
{
new counter();
}

}

心得:

1.在做图形化界面设计时一定要给按钮组件设置监听器

2.应该掌握swing包和awt包中的内容,以便能够正常使用

3.应该设置界面的大小尺寸与布局

posted on 2019-06-05 21:44  越活越酷  阅读(114)  评论(0编辑  收藏  举报

导航