import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;


public class num_1v extends JFrame{
    // 属性 -- 在多个方法中,要用到的组件,写在此处
    JTextField jf_s;
    JButton[] jb = new JButton[4];
    int num1,num2;
    char op;
    public num_1v(){
        // 做界面
        // 整体布局
        this.setLayout(new GridLayout(2,1));
        // 第一行
        jf_s = new JTextField(20);
        this.add(jf_s);
        // 第二行 -- 中间容器
        JPanel jp = new JPanel();
        jp.setLayout(new GridLayout(1,4));
        String[] str = {"1","2","+","="};
        for(int i = 0;i < str.length;i++){
            jb[i] = new JButton(str[i]);
            jp.add(jb[i]);
        }
        this.add(jp);
        // 绑定监听器
        jb[0].addActionListener(new NumberListener());
        jb[1].addActionListener(new NumberListener());
        jb[2].addActionListener(new OperaterListener());
        jb[3].addActionListener(new CalListener());
        // 显示
        this.setSize(400,200);
        this.setTitle("用户登录");
        this.setVisible(true);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    //数字键监听器
    class NumberListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e){
            //获取事件源
            JButton input = (JButton)e.getSource();
            if(input.equals(jb[0])){
                jf_s.setText(jf_s.getText() + "1");
            }else if(input.equals(jb[1])){
                jf_s.setText(jf_s.getText() + "2");
            }
        }
    }
    //符号建
    class OperaterListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e){
            //给num1赋值,给op赋值,清空文本框
            num1 = Integer.parseInt(jf_s.getText());
            //获取事件源
            JButton input = (JButton)e.getSource();
            if(input.equals(jb[2])){
                op = '+';
            }
            jf_s.setText("");
        }
    }
    //等于键
    class CalListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            //给num2赋值   num1和num2进行op这样的运算   把运算结果显示在jf上
            num2 = Integer.parseInt(jf_s.getText());
            int s = 0;
            switch (op) {
            case '+':
                s = num1 + num2;
                break;
            }
        jf_s.setText(s + "");
        }
    }
    public static void main(String[] args) {
        new num_1v();
    }
}

 

posted on 2019-05-20 20:02  Anonym_白熊  阅读(149)  评论(0编辑  收藏  举报