java简单计算器
package Calculator;
/**
*
* @author wanlin
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calculator2 extends JFrame implements ActionListener{
JTextField textfield1;
JTextField textfield2;
JTextField textfield3;
JLabel labe1;
JLabel labe2;
JLabel labe3;
JButton button1,button2,button3,button4;
Calculator2(){
setTitle("简单计算器-wanlin");
setBounds(800,200,380,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
init();
}
void init(){
Box box0 = Box.createHorizontalBox();
Box box1 = Box.createVerticalBox();
Box box2 = Box.createVerticalBox();
Box box3 = Box.createVerticalBox();
box1.add(new JLabel("操作数"));
box1.add(Box.createVerticalStrut(8));
box1.add(new JLabel("操作数"));
box1.add(Box.createVerticalStrut(8));
box1.add(new JLabel("结果"));
// box0.add(box1);
textfield1 = new JTextField(10);
textfield2 = new JTextField(10);
textfield3 = new JTextField(10);
box2.add(textfield1);
box2.add(Box.createVerticalStrut(8));
box2.add(textfield2);
box2.add(Box.createVerticalStrut(8));
box2.add(textfield3);
// box0.add(box2);
Panel pane1 = new Panel();
Panel pane2 = new Panel();
pane1.add(box1);
pane1.add(box2);
pane2.add(box3);
box0.add(pane1);
box0.add(pane2);
pane1.setBackground(Color.GREEN);
button1 = new JButton(" + ");
button2 = new JButton(" - ");
button3 = new JButton(" x ");
button4 = new JButton(" ÷ ");
box3.add(button1);
box3.add(Box.createVerticalStrut(12));
box3.add(button2);
box3.add(Box.createVerticalStrut(12));
box3.add(button3);
box3.add(Box.createVerticalStrut(12));
box3.add(button4);
box0.add(box3);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
add(box0);
}
public void actionPerformed(ActionEvent e){
String str1 = textfield1.getText();
String str2 = textfield2.getText();
// String str3 = textfield3.getText();
double x1 = Double.parseDouble(str1);
double x2 = Double.parseDouble(str2);
// double x3 = Double.parseDouble(str3);
double sum = 0;
try{
if(e.getSource() == button1){
sum = x1 + x2;
textfield3.setText(" "+sum);
}
else if(e.getSource() == button2){
sum = x1 - x2;
textfield3.setText(" "+sum);
}
else if(e.getSource() == button3){
sum = x1 * x2;
textfield3.setText(" "+sum);
}
else if (e.getSource() == button4){
sum = x1 / x2;
textfield3.setText(" "+sum);
}
}
catch(Exception ex){
System.out.println("eee");
}
}
public static void main(String[] args){
new Calculator2();
}
}