Java实现一个简单的计算器(流式布局)

实现一个计算器,运行界面如下:

Java实现一个简单的计算器(流式布局)_第1张图片
主要运用了Java的图形界面显示,流式布局方式,实现简单的加减乘除计算,结果显示在result文本框中

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Calculator extends JFrame {
 public Calculator(){
     setLayout(new FlowLayout(FlowLayout.LEFT,10,20));  //建立流式布局
     add(new JLabel("Number 1"));

     JTextField tf1 = new JTextField(3);  //文本框JTextFiled
     add(tf1);
     add(new JLabel("Number 2"));

     JTextField tf2 = new JTextField(3);  //文本框JTextFiled
     add(tf2);


     add(new JLabel("result"));

     JTextField tf3 = new JTextField(5);  //文本框JTextFiled
     add(tf3);

     JButton btnAdd = new JButton("Add");    //Add按钮引用对象名为btnAdd
     add( btnAdd);

     btnAdd.addActionListener(new ActionListener() {   //加一个监听器


        public void actionPerformed(ActionEvent e) {   //实现功能的方法

            double result = Double.parseDouble(tf1.getText()) +  Double.parseDouble(tf2.getText());
            tf3.setText(result+"");
        }

     });

     JButton btnSubtract = new JButton("Subtract");
     add(btnSubtract);

     btnSubtract.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {
            double result = Double.parseDouble(tf1.getText()) - Double.parseDouble(tf2.getText());
            tf3.setText(result+"");
        }

     });
     JButton btnMultiply = new JButton("Multiply");
     add(btnMultiply);

     btnMultiply.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {

            double result = Double.parseDouble(tf1.getText()) * Double.parseDouble(tf2.getText());
            tf3.setText(result+"");
        }

     });
     JButton btnDivide = new JButton("Divide");
     add(btnDivide);

     btnDivide.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {

            double result = Double.parseDouble(tf1.getText()) / Double.parseDouble(tf2.getText());
            tf3.setText(result+"");
        }

     });
 }
    public static void main(String[] args) {

        Calculator frame = new Calculator();
        frame.setTitle("Exercise16_4"); //设置标题
        frame.setSize(360,200);   //设置框的初始大小
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); /*设置关闭按钮*/
        frame.setVisible(true); //显示界面
    }

}

你可能感兴趣的:(Java,java,界面,布局,图形)