java编程简易计算器功能的模拟,完成加减乘除操作。
展开全部
源代码发给你参考下
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.border.EmptyBorder;
public class JiSuanQi extends JFrame implements ActionListener {
private JPanel cp;
private JTextField jtf3;
private JTextField jtf1;
private JTextField jtf2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JiSuanQi frame = new JiSuanQi();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public JiSuanQi() {
setTitle("简易计算器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(335, 185);
setLocationRelativeTo(null);
cp = new JPanel();
cp.setBorder(new EmptyBorder(5, 5, 5, 5));
cp.setLayout(new GridLayout(3, 1));
setContentPane(cp);
JPanel jp1 = new JPanel();
JLabel jl1 = new JLabel("操作数1");
JLabel jl2 = new JLabel("操作数2");
jtf1 = new JTextField(6);
jtf2 = new JTextField(6);
jp1.add(jl1);
jp1.add(jtf1);
jp1.add(jl2);
jp1.add(jtf2);
JPanel jp2 = new JPanel();
JButton jb1 = new JButton("加");
jb1.addActionListener(this);
JButton jb2 = new JButton("减");
jb2.addActionListener(this);
JButton jb3 = new JButton("乘");
jb3.addActionListener(this);
JButton jb4 = new JButton("除");
jb4.addActionListener(this);
jp2.add(jb1);
jp2.add(jb2);
jp2.add(jb3);
jp2.add(jb4);
JPanel jp3 = new JPanel();
JLabel jl4 = new JLabel("运行结果:");
jtf3 = new JTextField(12);
jp3.add(jl4);
jp3.add(jtf3);
cp.add(jp1);
cp.add(jp2);
cp.add(jp3);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
String result ;
double d1 = Double.parseDouble(jtf1.getText());
double d2 = Double.parseDouble(jtf2.getText());
if (command.equals("加")) {
result = (d1+d2)+"";
} else if (command.equals("减")) {
result = (d1-d2)+"";
} else if (command.equals("乘")) {
result = (d1*d2)+"";
} else if(command.equals("除")){
result = (d1/d2)+"";
}else{
result = "Error";
}
jtf3.setText(result);
}
}
追问
谢谢😁
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询