package com.hc.calc;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class Calc extends JFrame{
JPanel jp=new JPanel();
JLabel jl=new JLabel("第一个数");
JTextField jt=new JTextField(25);
JLabel jls=new JLabel("第二个数");
JTextField jts=new JTextField(25);
JButton add=new JButton("+");
JButton subtract=new JButton("-");
JButton multiply=new JButton("x");
JButton divide=new JButton("/");
JButton jbreturn=new JButton("退出");
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
new Calc();
}
public Calc() {
this.setSize(250, 300);
this.setTitle("calc");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(3);
jp.add(jl);
jp.add(jt);
jp.add(jls);
jp.add(jts);
jp.add(add);
jp.add(subtract);
jp.add(multiply);
jp.add(divide);
jp.add(jbreturn);
jbreturn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i=JOptionPane.showConfirmDialog(null, "确定退出?");
if (i==0) {
Calc.this.dispose();
}
}
});
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jt.setText(new BigDecimal(jt.getText()).add(new BigDecimal(jts.getText())).stripTrailingZeros().toPlainString());
jts.setText("");
}
});
subtract.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jt.setText(new BigDecimal(jt.getText()).subtract(new BigDecimal(jts.getText())).stripTrailingZeros().toPlainString());
jts.setText("");
}
});
multiply.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jt.setText(new BigDecimal(jt.getText()).multiply(new BigDecimal(jts.getText())).stripTrailingZeros().toPlainString());
jts.setText("");
}
});
divide.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MathContext mc=new MathContext(12,RoundingMode.HALF_DOWN);
jt.setText(new BigDecimal(jt.getText()).divide(new BigDecimal(jts.getText()),mc).stripTrailingZeros().toPlainString());
jts.setText("");
}
});
this.getContentPane().add(jp);
this.setVisible(true);
}
}