.利用GUI程序设计方法实现简单计算器的设计。运行效果可设计为如下界面,也可设计为windows系统中的计算器样式。
 (此程序为整数计算)
1 基础页面设计
 2 流布局器使用
 3 单选按钮注册监听事件
 4 文本框中内容获取,数据覆盖
除法
 
 乘法
 
package JiSuanQi;import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.temporal.JulianFields;public class jisuanqi extends JFrame {//重构无参构造方式jisuanqi(){//设置窗体标题this.setTitle("计算器");//确定窗体的位置,参数依次为 X坐标,Y坐标 ,长 ,高。this.setBounds(600,300,650,350);//设置页面可以关闭this.setDefaultCloseOperation(EXIT_ON_CLOSE);//获取内容面板容器Container c = getContentPane();//内容面板设置流布局,默认第四种,从左向右,hgap:水平间距 vgap:上下间距c.setLayout(new FlowLayout(FlowLayout.LEFT,60,75));/********************组件加入内容面板***********************************///构造文本框,标签,并将其放入内容面板TextField tf_A = new TextField(10);TextField tf_B = new TextField(10);TextField tf_C = new TextField(10);JLabel jl_A = new JLabel("+");JLabel jl_B = new JLabel("=");c.add(tf_A);c.add(jl_A);c.add(tf_B);c.add(jl_B);c.add(tf_C);//构造按钮,并加入内容面板JButton jb_A = new JButton("加");JButton jb_B = new JButton("减");JButton jb_C = new JButton("乘");JButton jb_D = new JButton("除");JButton jb_E = new JButton("清除");c.add(jb_A);c.add(jb_B);c.add(jb_C);c.add(jb_D);c.add(jb_E);/********************给按钮注册监听器****************************************///给”加“按钮写触发事件 new ActionLinster() 为触发事件,也可以建立触发事件的对象,注册监听时直接引用,如下//法 1jb_A.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {//获取文本框中的内容(注意获取的数据类型为字符串)String strA = tf_A.getText();String strB = tf_B.getText();String strC = " "+(Integer.parseInt(strA)+Integer.parseInt(strB));tf_C.setText(strC);}});//法 2//对”减“设置触发事件ActionListener eventB = new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {String strA = tf_A.getText();String strB = tf_B.getText();String strC = " "+(Integer.parseInt(strA)-Integer.parseInt(strB));tf_C.setText(strC);}};//将触发事件注册给”减“jb_B.addActionListener(eventB);//对”乘“绑定监听jb_C.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {String strA = tf_A.getText();String strB = tf_B.getText();String strC = " "+(Integer.parseInt(strA)*Integer.parseInt(strB));tf_C.setText(strC);}});//对”除“绑定监听事件(注意,除法可能会有小数,所以将数字处理为double 这里*1.0隐式转换)jb_D.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {String strA = tf_A.getText();String strB = tf_B.getText();String strC = " "+(1.0*Integer.parseInt(strA)/Integer.parseInt(strB));tf_C.setText(strC);}});//对”清空“绑定监听事件jb_E.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {//文本清空,可以用空字符串覆盖文本tf_A.setText("");tf_B.setText("");tf_C.setText("");}});/***********************************************///界面可视化setVisible(true);}public static void main(String[] args) {new jisuanqi();}
}
欢迎交流
















