用Java编写实现加减乘除,界面如下
展开全部
用Java编写的实现加减乘除的程序如下
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator extends JFrame implements ActionListener{
JLabel jl1=new JLabel("第一个数");
JLabel jl2=new JLabel("运算符");
JLabel jl3=new JLabel("第二个数");
JLabel jl4=new JLabel("结果:");
JTextField jtf1=new JTextField(8);
JTextField jtf2=new JTextField(8);
JTextField jtf3=new JTextField(8);
String a[]={"+","-","*","/"};
JComboBox<String> jcb=new JComboBox<String>(a);
JButton jb1=new JButton("计算");
JButton jb2=new JButton("退出");
JPanel jp=new JPanel();
Calculator(){
setTitle("计算器");
jb1.addActionListener(this);
jb2.addActionListener(this);
jp.setLayout(null);
jl1.setBounds(30, 30, 80, 20);
jl2.setBounds(110, 30, 80, 20);
jl3.setBounds(190, 30, 80, 20);
jtf1.setBounds(30, 60, 70, 20);
jcb.setBounds(110, 60, 70,20);
jtf2.setBounds(190, 60, 70, 20);
jl4.setBounds(80, 110, 40, 20);
jtf3.setBounds(110, 110, 100, 20);
jb1.setBounds(60, 160, 60, 25);
jb2.setBounds(170, 160, 60, 25);
jp.add(jl1);jp.add(jl2);jp.add(jl3);
jp.add(jtf1);jp.add(jcb);jp.add(jtf2);
jp.add(jl4);jp.add(jtf3);
jp.add(jb1);jp.add(jb2);
add(jp,BorderLayout.CENTER);
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Calculator();
}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==jb1){
String c=((String) jcb.getSelectedItem()).trim();
if(jtf1.getText().trim().equals("")){
JOptionPane.showMessageDialog(this, "第一个数不能为空");
jtf1.requestFocus();
return;
}
if(jtf2.getText().trim().equals("")){
JOptionPane.showMessageDialog(this, "第二个数不能为空");
jtf2.requestFocus();
return;
}
double num1=Double.parseDouble(jtf1.getText().trim());
double num2=Double.parseDouble(jtf2.getText().trim());
double num3 = 0;
switch(c){
case "+":num3=num1+num2;break;
case "-":num3=num1-num2;break;
case "*":num3=num1*num2;break;
case "/":
if(num2==0){
JOptionPane.showMessageDialog(this, "除数不能为0");
jtf2.requestFocus();
return;
}else{
num3=num1/num2;
break;
}
}
jtf3.setText(String.valueOf(num3));
}
if(ae.getSource()==jb2){
System.exit(0);
}
}
}
运行结果
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询