package Calculator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* Created with IntelliJ IDEA.
*
* @Author: LSheng
* @Date: 2022/11/25/13:03
* @Description:
*/
public class calculator extends JFrame {
public calculator() {
Container cp = getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.LEFT, 100,75));
TextField tf_1 = new TextField();
TextField tf_2 = new TextField();
TextField tf_3 = new TextField();
JLabel jl1 = new JLabel("+");
JLabel jl2 = new JLabel("=");
cp.add(tf_1);
cp.add(jl1);
cp.add(tf_2);
cp.add(jl2);
cp.add(tf_3);
JButton jb1 = new JButton("加");
JButton jb2 = new JButton("减");
JButton jb3 = new JButton("乘");
JButton jb4 = new JButton("除");
JButton jb5 = new JButton("清除");
cp.add(jb1);
cp.add(jb2);
cp.add(jb3);
cp.add(jb4);
cp.add(jb5);
//加法,给按钮注册监听器
jb1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
String str1 = tf_1.getText();
String str2 = tf_2.getText();
String str3 = " " + (Integer.parseInt(str1) + Integer.parseInt(str2));
tf_3.setText(str3);
}
});
jb2.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
String str1 = tf_1.getText();
String str2 = tf_2.getText();
String str3 = " " + (Integer.parseInt(str1) - Integer.parseInt(str2));
tf_3.setText(str3);
}
});
jb3.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
String str1 = tf_1.getText();
String str2 = tf_2.getText();
String str3 = " " + (Integer.parseInt(str1) * Integer.parseInt(str2));
tf_3.setText(str3);
}
});
jb4.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
String str1 = tf_1.getText();
String str2 = tf_2.getText();
String str3 = " " + (1.0*Integer.parseInt(str1) / Integer.parseInt(str2));
tf_3.setText(str3);
}
});
jb5.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
tf_1.setText("");
tf_2.setText("");
tf_3.setText("");
}
});
setVisible(true);
}
public static void main(String[] args) {
JFrame ca = new JFrame("计算器");
ca.setTitle("计算器");
ca.setBounds(200,300,200,300);
ca.setDefaultCloseOperation(EXIT_ON_CLOSE);
new calculator();
}
}
代码运行后在左上角会弹出
点击方括号,进入计算器界面
则可进行计算。简单代码实现,有不足之处,多多交流