Java实战(四)定义一个GUI程序,实现简易的算术运算
定义一个GUI程序,实现简易的算术运算
(1)定义窗口类,Grid布局,第一行输入第一个数据,第二行通过choice选择 + - * /,第三行输入第二个数据,第四行按钮,计算和退出 (2)定义事件处理程序,实现计算和退出功能(计算结果可以采用System.out.println()输出) (3)定义测试类
实现代码:
package CurriculumDesign; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /* 3.定义一个GUI程序,实现简易的算术运算。 (1)定义窗口类,Grid布局,第一行输入第一个数据,第二行通过choice选择 + - * /,第三行输入第二个数据,第四行按钮,计算和退出 (2)定义事件处理程序,实现计算和退出功能(计算结果可以采用System.out.println()输出) (3)定义测试类 */ class MyCalc extends Frame { //组件准备 //第一个数据输入文本域 TextField parameter1 = new TextField(); //操作符选择下拉框 Choice sexChoice = new Choice(); //第二个数据输入文本域 TextField parameter2 = new TextField(); //计算按钮 Button doButton = new Button("开始计算"); //退出按钮 Button exitButton = new Button("退出程序"); //定义构造函数 public MyCalc(int x, int y, int width, int height, Color color) { //设置窗口名称 super("MyFrame"); //设置可见性 setVisible(true); //弹出的初始位置 setLocation(x, y); //设置窗口大小 setSize(width, height); //设置背景颜色 setBackground(color); //设置窗口大小不可改变 setResizable(false); //初始化窗口 init(); } //窗口初始化 public void init() { //网格布局,4行2列 setLayout(new GridLayout(4,2)); //第一行,一个标签 + 一个文本域 add(new Label("请输入第一个数")); add(parameter1); //第二行,一个标签 + 选择框 add(new Label("请选择操作符")); sexChoice.add("+"); sexChoice.add("-"); sexChoice.add("*"); sexChoice.add("/"); add(sexChoice); //第三行,一个标签 + 一个文本域 add(new Label("请输入第二个数")); add(parameter2); //第四行,两个按钮 add(doButton); add(exitButton); //为按钮添加监听器 doButton.addActionListener(new MyLintener()); exitButton.addActionListener(new MyLintener()); } //定义监听器内部类(内部类方便使用外层类属性和方法) class MyLintener implements ActionListener { //实现接口 @Override public void actionPerformed(ActionEvent e) { //这里实现了利用一个监听器监听多个按钮对象 //这里当点击按钮时会按照相应按钮指令信息进入不同代码块 //如果上面不使用方法setActionCommand("xx")设置按钮指令信息的话 //这里返回的ActionEvent对象获得的指令默认为按钮名称 //若点击的是【开始计算按钮】 if (e.getActionCommand() == "开始计算") { //获取文本域中的信息 String str1= parameter1.getText(); String str2= parameter2.getText(); //为了进行计算,需要转化为int型 int p1 = Integer.parseInt(str1); int p2 = Integer.parseInt(str2); //获得操作符信息 String operate = sexChoice.getSelectedItem(); //用于承接计算结果 int result = 0; //根据操作符不同进行不同的操作 switch (operate.charAt(0)) { case +: result = p1 + p2; break; case -: result = p1 - p2; break; case *: result = p1 * p2; break; case /: result = p1 / p2; break; default: break; } //打印结果 System.out.println("运算结果为:" + result); } //若点击的是【退出程序按钮】 else if (e.getActionCommand() == "退出程序") { //退出程序 System.exit(0); } } } } public class Test4 { //把关闭窗口的功能拿出来单独写一个方法,就可以点窗口上的X关闭窗口了 //这个方法题目并没有要求,但是习惯上加上一个 private static void windowClose(Frame frame){ frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { //这里创建一个MyFrame对象并直接传进静态方法windowClose()中 windowClose(new MyCalc(300,300,300,200,Color.pink)); } }
运行结果:
-
窗口样式:
-
进行操作( 3+3=6、3-3=0、3*3=9、3/3=1 ):
-
点击退出程序后成功关闭窗口
上一篇:
多线程四大经典案例