标题图
目的
1 事件机制
2 单选按钮及事件
要求
1. 实现一个计算器(能实现加减乘除运算 )
图片
2.实现界面上单选按钮中的事件
当按下某一单选按钮时将结果显示到最后一个输入框
3.当用户输入错误时提示。提示“请输入数字”,输入的值可以整数或小数。不能是其它字符
捕获输入错误时的异常,给出相应提示到结果框。
实验步骤:
1.定义类显示窗口,标题为“计算器”
2.在类中添加窗口组件作为类的成员变量,
JLabel文本,
JRadioButton为单选按钮,
JTextField为输入框,
JPanel为容器,
ButtonGroup 为单选组按钮
3.在构造方法为每个组件及容器申请内存空间
4.设置窗口的布局为网格布局,有4行1列
5.将所有组件添加到容器中,将单选按钮再次添加到ButtonGroup,再添加容器到窗口
6.实现ItemListener接口,并实现itemStateChanged方法,在方法判断事件源,根据用户选择进行算术运算,将计算结果显示到第三个输入框。添加给事件源添加监听。
7.捕获输入错误时的异常NumberFormatException,并给出错误提示到输入框中。
代码
import java.awt.FlowLayout;import java.awt.GridLayout;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import javax.swing.*;public class CaculateDemo extends JFrame implements ItemListener{//在类中添加窗口组件作为类的成员变量//JLabel文本
JLabel j11,j12,j13;//JTextField为输入框
JTextField jtf1,jtf2,jtf3;//JPanel为容器
JPanel jp1,jp2,jp3,jp4;//JRadioButton为单选按钮
JRadioButton j1,j2,j3,j4;//ButtonGroup 为单选组按钮
ButtonGroup gd;
CaculateDemo(){//在构造方法为每个组件及容器申请内存空间
super("计算器");
j11=new JLabel("操作数1");
j12=new JLabel("操作数2");
j13=new JLabel("计算结果是:");
jtf1=new JTextField(10);
jtf2=new JTextField(10);
jtf3=new JTextField(10);
jp1=new JPanel();
jp2=new JPanel();
jp3=new JPanel();
jp4=new JPanel();
j1=new JRadioButton("+");
j2=new JRadioButton("-");
j3=new JRadioButton("*");
j4=new JRadioButton("/");
gd=new ButtonGroup();
} public void init(){ this.setSize(300,300); this.setLocation(100,100); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); this.setLayout(new GridLayout(4,1));
jp1.setLayout(new FlowLayout(FlowLayout.LEFT));
jp2.setLayout(new FlowLayout(FlowLayout.LEFT));
jp3.setLayout(new FlowLayout(FlowLayout.LEFT));
jp4.setLayout(new FlowLayout(FlowLayout.LEFT));
//在容器1中加文本,输入框
jp1.add(j11);
jp1.add(jtf1); //在容器2中加文本,输入框
jp2.add(j12);
jp2.add(jtf2);
jp3.add(j1);
jp3.add(j2);
jp3.add(j3);
jp3.add(j4);
gd.add(j1);
gd.add(j2);
gd.add(j3);
gd.add(j4);
//在容器4中加文本,输入框
jp4.add(j13);
jp4.add(jtf3);
this.add(jp1); this.add(jp2); this.add(jp3); this.add(jp4);
//添加给事件源添加监听
j1.addItemListener(this);
j2.addItemListener(this);
j3.addItemListener(this);
j4.addItemListener(this);
}
public static void main(String[] args) { new CaculateDemo().init();
} //实现itemStateChanged方法
@Override
public void itemStateChanged(ItemEvent e) {
try{ double num1=Double.parseDouble(jtf1.getText()); double num2=Double.parseDouble(jtf2.getText()); double res=0;
if(e.getSource()==j1){
res=num1+num2;
}else if(e.getSource()==j2){
res=num1-num2;
}else if(e.getSource()==j3){
res=num1*num2;
}else if(e.getSource()==j4){
res=num1/num2;
}
jtf3.setText(res+"");
} //捕获输入错误时的异常NumberFormatException,并给出错误提示到输入框中
catch(NumberFormatException eee){
jtf3.setText("请输入数字");
}
}
}运行结果图
图片
作者:达叔小生
链接:https://www.jianshu.com/p/028293f24c41
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦


