import java.awt.FlowLayout;
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 CalFrame extends JFrame {
private void init() {
FlowLayout flc = new FlowLayout(FlowLayout.CENTER);
this.setSize(new Dimension(300, 200));
this.setLayout(flc);
JPanel jp = new JPanel(flc);
final JTextField num1 = new JTextField();
num1.setColumns(5);
final JTextField num2 = new JTextField();
num2.setColumns(5);
final JTextField res = new JTextField();
res.setColumns(5);
final JComboBox c = new JComboBox(
new Character[] { '+', '-', '*', '/' });
jp.add(num1);
jp.add(c);
jp.add(num2);
jp.add(new JLabel("="));
jp.add(res);
this.add(jp);
JButton jbt = new JButton("计算");
jbt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
double result = 0;
try {
num1.setText(num1.getText().replaceAll("\\D", ""));
num2.setText(num2.getText().replaceAll("\\D", ""));
double d1 = Double.parseDouble(0+num1.getText());
double d2 = Double.parseDouble(0+num2.getText());
char cc = c.getSelectedItem().toString().charAt(0);
switch (cc) {
case '+':
result = d1 + d2;
break;
case '-':
result = d1 - d2;
break;
case '*':
result = d1 * d2;
break;
case '/':
result = d1 / d2;
break;
default:
break;
}
res.setText(String.valueOf(result));
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
"Error:" + e.getMessage());
}
}
});
this.add(jbt);
}
public CalFrame() {
init();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new CalFrame();
}
}