创建一个窗口实现四则运算
图片
import com.sun.imageio.plugins.gif.GIFImageReader;
import jdk.nashorn.internal.scripts.JO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class fourArithmetic extends JFrame {
public fourArithmetic(){
this.setSize(400,200);
// this.setLocation(100,100);
this.setLocationRelativeTo(null);
this.setTitle("四则运算");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setIconImage(new ImageIcon("fourArithmetic.png").getImage());
this.setLayout(new GridLayout(3,1));
JPanel jp = new JPanel();
JPanel jp1 = new JPanel();
JPanel jp2 = new JPanel();
JButton jb = new JButton("=");
jb.setSize(30,10);
JTextField num = new JTextField(6);
JTextField num1 = new JTextField(2);
JTextField num2 = new JTextField(6);
JTextField num3 = new JTextField(6);
jp1.add(num);
jp1.add(num1);
jp1.add(num2);
jp1.add(jb);
jp1.add(num3);
this.add(jp);
this.add(jp1);
this.add(jp2);
this.setVisible(true);
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
String Num = num.getText();
String Num1 = num1.getText();
String Num2 = num2.getText();
if (Num.length() == 0 || Num1.length() == 0 || Num2.length() == 0) {
JOptionPane.showMessageDialog(null, "输入不能为空!", "系统提示", JOptionPane.WARNING_MESSAGE);
return;
}
if (Num.matches("[0-9]+") && Num2.matches("[0-9]+")) {
if (Num1.equals("+") || Num1.equals("-") || Num1.equals("*") || Num1.equals("/")) {
double a1 = new Double(Num);
double a2 = new Double(Num2);
if (Num1.equals("+")) {
num3.setText("" + (a1 + a2));
} else if (Num1.equals("-")) {
num3.setText("" + (a1 - a2));
} else if (Num1.equals("*")) {
num3.setText("" + a1 * a2);
} else {
num3.setText("" + a1 / a2);
}
} else {
JOptionPane.showMessageDialog(null, "运算符号有误!");
return;
}
} else {
JOptionPane.showMessageDialog(null, "请输入数字进行运算!");
return;
}
}catch (ArithmeticException e1) {
JOptionPane.showMessageDialog(null, "除数不能为0!");
return;
}
}
});
}
public static void main(String[] args) {
new fourArithmetic();
}
}