java第四章实现迷你计算器_SWUST--Java实验(四) 简单计算器

import java.awt.BorderLayout;

import java.awt.FlowLayout;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.BorderFactory;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JTextField;

public class Demo extends JFrame {

JPanel jp1 = new JPanel();

JPanel jp2 = new JPanel();

JPanel jp3 = new JPanel();

JButton bt1 = new JButton("+");

JButton bt2 = new JButton("-");

JButton bt3 = new JButton("*");

JButton bt4 = new JButton("/");

JTextField jf1 = new JTextField();

JTextField jf2 = new JTextField();

JTextField jf3 = new JTextField("我来显示");

JLabel jl1 = new JLabel("运算结果:");

JLabel jl2 = new JLabel("+");

public Demo() {

setBounds(100,100,200,200);

setTitle("简易Windows计算器");

jf1.setColumns(6);

jf2.setColumns(6);

jf3.setColumns(12);

jp1.setLayout(new GridLayout(2,2));

jp1.add(bt1);

jp1.add(bt2);

jp1.add(bt3);

jp1.add(bt4);

jp2.setLayout(new FlowLayout());

jp2.add(jl1);

jp2.add(jf3);

jp3.setLayout(new FlowLayout());

jp3.add(jf1);

jp3.add(jl2);

jp3.add(jf2);

setLayout(new BorderLayout()); //控制布局

add("South",jp1);

add("North",jp3);

add("Center",jp2);

bt1.addActionListener(new ActionListener() { //按钮'+'加监听

@Override

public void actionPerformed(ActionEvent arg0) {

jl2.setText("+"); //设置显示的符号

String x1 = jf1.getText(); //赋值键入的数据

String x2 = jf2.getText();

int s1 = Integer.parseInt(x1); //转换为整数

int s2 = Integer.parseInt(x2);

int s3 = s1 + s2; //运算

jf3.setText(s3+""); //中间的文本框显示结果

}

});

bt2.addActionListener(new ActionListener() { //同上

@Override

public void actionPerformed(ActionEvent arg0) {

jl2.setText("-");

String x1 = jf1.getText();

String x2 = jf2.getText();

int s1 = Integer.parseInt(x1);

int s2 = Integer.parseInt(x2);

int s3 = s1 - s2;

jf3.setText(s3+"");

}

});

bt3.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent arg0) {

jl2.setText("*");

String x1 = jf1.getText();

String x2 = jf2.getText();

int s1 = Integer.parseInt(x1);

int s2 = Integer.parseInt(x2);

int s3 = s1 * s2;

jf3.setText(s3+"");

}

});

bt4.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent arg0) {

jl2.setText("/");

String x1 = jf1.getText();

String x2 = jf2.getText();

int s1 = Integer.parseInt(x1);

int s2 = Integer.parseInt(x2);

int s3 = s1 / s2;

jf3.setText(s3+"");

}

});

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true);

}

public static void main(String[] args) {

new Demo();

}

}

你可能感兴趣的:(java第四章实现迷你计算器)