编写一个Java小应用程序,设计4个按钮,分别命名为“加”、“差”、“积”、“除”...

2020-06-27 社会 77阅读
;
 
 
可以这样写:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleCalc extends JApplet implements ActionListener {
    public static void main(String[] args) {    // 这 main 方法只在调试时用到
        SimpleCalc sc = new SimpleCalc();
        sc.init();
        JFrame f = new JFrame();
        f.add(sc);
        f.pack();
        f.setVisible(true);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
    }
    private JTextField num1 = new JTextField(),
                       num2 = new JTextField(),
                       result = new JTextField(20);
    public void init() {
        setLayout(new GridLayout(0, 2, 2, 2));
        add(num1);
        add(num2);
        for (String cmd: new String[]{"加", "差", "积", "除"}) {
            JButton b = new JButton(cmd);
            b.addActionListener(this);
            add(b);
        }
        add(new JLabel("结果:", JLabel.TRAILING));
        add(result);
        result.setEditable(false);
        getRootPane().setBorder(BorderFactory.createRaisedBevelBorder());
    }
    public void actionPerformed(ActionEvent e) {
        try {
            double n1 = Double.valueOf(num1.getText()),
                   n2 = Double.valueOf(num2.getText());
            String cmd = e.getActionCommand();
            if (cmd == "加") result.setText(n1 + n2 + "");
            if (cmd == "差") result.setText(n1 - n2 + "");
            if (cmd == "积") result.setText(n1 * n2 + "");
            if (cmd == "除") result.setText(n1 / n2 + "");
        } catch (NumberFormatException nfe) {
            JOptionPane.showMessageDialog(this, "数字个数或格式错误!",
                    "", JOptionPane.ERROR_MESSAGE);
        }
    }
}
 
 
 
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com