很简单但是浪费很多时间在无用功上面。
package src.test;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class examplethree extends JFrame {
JTextField inputField;
JPanel p1=new JPanel();
JPanel p2=new JPanel();
double result;//计算结果
String symbol;//运算符号
boolean ok;
public void addButton(String a, ActionListener cc){
JButton button = new JButton(a);
button.addActionListener(cc);
p2.add(button);
}
public examplethree(){
JMenuBar menubar=new JMenuBar();
this.setJMenuBar(menubar);
JMenu menu1=new JMenu("简单");
JMenu menu2=new JMenu("完整");
JMenu menu3=new JMenu("科学");
menubar.add(menu1);
menubar.add(menu2);
menubar.add(menu3);
symbol="=";
this.setTitle("计算器");
this.setSize(200, 300);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
inputField = new JTextField(20);
p1.add(inputField);
this.add(p1,BorderLayout.NORTH);
p2.setLayout(new GridLayout(4, 4 , 6, 6));
class Action1 implements ActionListener{
public void actionPerformed(ActionEvent e){
String input=e.getActionCommand();
inputField.setText(inputField.getText()+input);
if(ok){
inputField.setText("");
ok = false;
}
}
}
class Action2 implements ActionListener{
public void actionPerformed(ActionEvent e){
String input=e.getActionCommand();
if(ok){
symbol = input;
}
else{
if(symbol.equals("+")){
result +=Double.parseDouble(inputField.getText());
}
else if(symbol.equals("-")){
result -=Double.parseDouble(inputField.getText());
}
else if(symbol.equals("*")){
result *=Double.parseDouble(inputField.getText());
}
else if(symbol.equals("/")){
result /=Double.parseDouble(inputField.getText());
}else {
result =Double.parseDouble(inputField.getText());
}
inputField.setText(result+"");
symbol=input;
ok=true;
}
}
}
class Action3 implements ActionListener{
public void actionPerformed(ActionEvent e){
String input=e.getActionCommand();
if(input.equals("C")){
inputField.setText("0");
ok = true;
}
}
}
menu2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JPanel panel1=new JPanel();
JLabel label=new JLabel("wobu",JLabel.CENTER);
label.setFont(new Font("宋体",Font.PLAIN,20));
panel1.add(label);
panel1.setVisible(true);
}
});
Action1 a1 = new Action1();
Action2 a2 = new Action2();
Action3 a3 = new Action3();
this.addButton("7",a1);
this.addButton("8",a1);
this.addButton("9",a1);
this.addButton("+",a2);
this.addButton("4",a1);
this.addButton("5",a1);
this.addButton("6",a1);
this.addButton("-",a2);
this.addButton("1",a1);
this.addButton("2",a1);
this.addButton("3",a1);
this.addButton("*",a2);
this.addButton("0",a1);
this.addButton("C",a3);
this.addButton("=",a2);
this.addButton("/",a2);
this.add(p2,BorderLayout.SOUTH);
this.pack();
}//构造方法
public static void main(String[] args){
new examplethree();
}
}