簡單寫了下,代碼如下請參照:
創(chuàng)新互聯(lián)建站主要從事網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)臨湘,十年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):028-86922220
/**
*?計(jì)算器類
*?
*?@author?Administrator
*
*/
public?class?Calculator?extends?JFrame?implements?ActionListener?{
private?static?final?long?serialVersionUID?=?3868243398506940702L;
//?文本框
private?JTextField?result;
//?按鈕數(shù)組
private?JButton[]?buttons;
//?按鈕文本
private?final?String[]?characters?=?{?"7",?"8",?"9",?"/",?"4",?"5",?"6",
"*",?"1",?"2",?"3",?"-",?"0",?".",?"=",?"+"?};
//?是否為第一個輸入的數(shù)字
private?boolean?isFirstDigit?=?true;
//?運(yùn)算結(jié)果
private?double?resultNum?=?0.0;
//?運(yùn)算符
private?String?operator?=?"=";
public?Calculator(String?title)?{
//?設(shè)置標(biāo)題欄
super(title);
//?初始化各組件
init();
//?注冊各組件監(jiān)聽器
registerListener();
//?顯示窗體
setVisible(true);
}
/**
*?初始化各組件
*/
private?void?init()?{
//?常用屬性初始化
setSize(220,?200);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
/*?文本框?qū)ο蟪跏蓟?*/
result?=?new?JTextField("0");
//?文本右對齊
result.setHorizontalAlignment(JTextField.RIGHT);
//?設(shè)置是否可編輯
result.setEditable(false);
/*?按鈕初始化?*/
buttons?=?new?JButton[characters.length];
for?(int?i?=?0;?i??buttons.length;?i++)?{
buttons[i]?=?new?JButton(characters[i]);
buttons[i].setFocusable(false);?//?不允許按鈕定位焦點(diǎn)
}
/*?將文本框與按鈕添加到窗體中?*/
add(result,?BorderLayout.NORTH);
JPanel?pnl?=?new?JPanel(new?GridLayout(4,?4,?5,?5));
for?(JButton?jButton?:?buttons)?{
pnl.add(jButton);
}
add(pnl);
this.getContentPane().setFocusable(true);
}
/**
*?注冊監(jiān)聽器
*/
private?void?registerListener()?{
for?(JButton?jButton?:?buttons)?{
jButton.addActionListener(this);
}
//?注冊鍵盤事件
this.getContentPane().addKeyListener(new?KeyAdapter()?{
@Override
public?void?keyPressed(KeyEvent?e)?{
String?text?=?String.valueOf(e.getKeyChar());
if?(Character.isDigit(text.charAt(0))?||?".".equals(text))?{?//?數(shù)字或小數(shù)點(diǎn)
handleNumber(text);
}?else?if?("+-*/=".indexOf(text)?!=?-1)?{?//?運(yùn)算符
handleOperator(text);
}?else?if?(e.getKeyCode()?==?8)?{?//?退格鍵
String?tmp?=?result.getText().trim();
if?(tmp.length()?==?1)?{
result.setText("0");
isFirstDigit?=?true;
}?else?{
result.setText(tmp.substring(0,?tmp.length()?-?1));
}
}
}
});
}
@Override
public?void?actionPerformed(ActionEvent?e)?{
JButton?btn?=?(JButton)?e.getSource();
String?text?=?btn.getText().trim();
if?(Character.isDigit(text.charAt(0))?||?".".equals(text))?{?//?處理數(shù)字和小數(shù)點(diǎn)
handleNumber(text);
}?else?{?//?處理運(yùn)算符
handleOperator(text);
}
}
/**
*?處理數(shù)字和小數(shù)點(diǎn)
*?
*?@param?text
*/
private?void?handleNumber(String?text)?{
if?(isFirstDigit)?{?//?第一次輸入
if?(".".equals(text))?{
this.result.setText("0.");
}?else?{
this.result.setText(text);
}
}?else?if?("0".equals(text)??"0".equals(this.result.getText()))?{
isFirstDigit?=?true;
return;
}?else?if?(".".equals(text)??this.result.getText().indexOf(".")?==?-1)?{
this.result.setText(this.result.getText()?+?".");
}?else?if?(!".".equals(text))?{
this.result.setText(this.result.getText()?+?text);
}
isFirstDigit?=?false;
}
/**
*?處理運(yùn)算符
*?
*?@param?text
*/
private?void?handleOperator(String?text)?{
switch?(operator)?{?//?處理各項(xiàng)運(yùn)算??適用于JDK1.7版本的
case?"+":
resultNum?+=?Double.parseDouble(this.result.getText());
break;
case?"-":
resultNum?-=?Double.parseDouble(this.result.getText());
break;
case?"*":
resultNum?*=?Double.parseDouble(this.result.getText());
break;
case?"/":
resultNum?/=?Double.parseDouble(this.result.getText());
break;
case?"=":
resultNum?=?Double.parseDouble(this.result.getText());
break;
}
//?將文本框的值修改為運(yùn)算結(jié)果
this.result.setText(String.valueOf(resultNum));
//?將點(diǎn)擊的運(yùn)算符放入operator保存
operator?=?text;
//?下一個數(shù)字第一次點(diǎn)擊
isFirstDigit?=?true;
}
public?static?void?main(String[]?args)?{
?new?Calculator("My?Calculator");
?}
}
運(yùn)行結(jié)果如下:
import java.awt.*;
import java.awt.event.*;
public class lvhaiya{
int tmp,sum,sum1,sum2=1,sum3=1;
String a,b,c,d;String s="";
Frame f=new Frame("計(jì)算器");
private String[]name={
"0","1","2","3","4","5","6","7","8","9","+","-","*","/","=","空格"
};
public Button[] button=new Button[name.length];
TextField t=new TextField("",30);
Panel p=new Panel();
Panel p1=new Panel();
Color color=new Color(100,170,90);
public lvhaiya(){
p1.setLayout(new GridLayout(5,5));
for(int i=0;iname.length;i++){
button[i]=new Button(name[i]);
p1.add(button[i]);
}
p.setLayout(new FlowLayout(FlowLayout.LEFT));
p.setBackground(color);
p.add(t);
f.add(p,BorderLayout.NORTH);
f.add(p1,BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
f.addWindowListener( new WindowClose());
t.setText("0.");
for(int i=0;iname.length;i++){
button[i].addActionListener(new ButtonEventl());
}
}
public static void main(String[]args){
new lvhaiya();
}
class WindowClose extends WindowAdapter{
public void windouClosing(WindowEvent e){
System.exit(0);
}
}
class ButtonEventl implements ActionListener{
public void actionPerformed(ActionEvent e)throws ArithmeticException{
String command=e.getActionCommand();
if(command.equals("+")){
sum=Integer.parseInt(t.getText())+sum;
t.setText(String.valueOf(sum));
a=t.getText();
s="";
}
else if(command.equals("-")){
sum1=Integer.parseInt(t.getText());
b=t.getText();
s="";
}
else if(command.equals("*")){
sum2=Integer.parseInt(t.getText())*sum2;
t.setText(String.valueOf(sum2));
c=t.getText();
s="";
}
else if(command.equals("/")){
sum3=Integer.parseInt(t.getText());
d=t.getText();
s="";
}
else if(command.equals("=")){
if(a!=null){
t.setText(String.valueOf(sum+tmp));
}
if(b!=null){
t.setText(String.valueOf(sum1-tmp));
}
if(c!=null){
t.setText(String.valueOf(sum2*tmp));
}
try{
if(d!=null){
t.setText(String.valueOf(sum3/tmp));
}
}
catch(ArithmeticException a){
t.setText("除數(shù)不能為零");
}
}
else if(command.equals("空格")){
sum=0;
a=null;
b=null;
c=null;
d=null;
sum1=0;
sum2=1;
sum3=1;
tmp=0;
t.setText("0");
s="";
}
else{
s=s+command;
t.setText(s);
tmp=Integer.parseInt(s);
}
}
}
}
//按鈕可以自己美化一下 希望可以幫到你
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
class Normal{
double i,j;
public Normal(double num1,double num2){
i=num1;
j=num2;
}
public double puls(){
return i+j;
}
public double subtract(){
return i-j;
}
public double multiply(){
return i*j;
}
public double divide(){
return i/j;
}
public double surpuls(){
return i%j;
}
}
class scientific extends Normal{
public scientific(int num1, int num2) {
super(num1, num2);
}
}
public class calc extends JFrame{
public static void main(String[] args) {
viewNormal VN= new viewNormal("normal");
}
}
class viewNormal extends JFrame implements ActionListener{
JPanel jp1 = new JPanel(new GridLayout(4,3,5,5));
JPanel jp2 = new JPanel(new GridLayout(5,1,5,5));
JLabel jl;
JButton[] jb;
JButton jbs,jbo,jba,jbb,jbc,jby;
StringBuffer sb = new StringBuffer();
Normal normal;
int dot=0;
double fnum=0;
double lnum=0;
double result;
String sign=null;
public viewNormal(String title){
setTitle(title);
setLayout(null);
setVisible(true);
setBounds(200,200,305,350);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
jb= new JButton[12];
for(int i=0;i9;i++){
jb[i]=new JButton(""+(i+1));
jp1.add(jb[i]);
jb[i].addActionListener(this);
}
jb[9]=new JButton(".");
jb[10]=new JButton("0");
jb[11]=new JButton("=");
jb[9].addActionListener(this);
jb[10].addActionListener(this);
jb[11].addActionListener(this);
jp1.add(jb[9]);
jp1.add(jb[10]);
jp1.add(jb[11]);
jp1.setBounds(10, 100, 200, 200);
jbs= new JButton("+");jbo= new JButton("-");jba= new JButton("*");
jbb= new JButton("/");jby= new JButton("%");jbc= new JButton("C");
jbs.addActionListener(this);jbo.addActionListener(this);jba.addActionListener(this);
jbb.addActionListener(this);jby.addActionListener(this);jbc.addActionListener(this);
//jp2.add(jby);
jp2.add(jbs);jp2.add(jbo);jp2.add(jba);jp2.add(jbb);jp2.add(jbc);
jp2.setBounds(215, 100, 70, 200);
jl= new JLabel("0",JLabel.RIGHT);
jl.setFont(new Font("Batang",Font.BOLD, 20));
jl.setBorder(new LineBorder(Color.black,2));
jl.setBackground(Color.white);
jl.setBounds(10, 40, 275, 50);
jl.setOpaque(true);
add(jl);
add(jp1);
add(jp2);
}
//+
public void sum(){
lnum=Double.parseDouble(sb.toString());
normal=new Normal(fnum,lnum);
fnum=normal.puls();
result=fnum;
}
//-
private void sub() {
System.out.println(sb.toString());
lnum=Double.parseDouble(sb.toString());
normal=new Normal(fnum,lnum);
fnum=normal.subtract();
result=fnum;
}
//*
private void mul() {
lnum=Double.parseDouble(sb.toString());
normal=new Normal(fnum,lnum);
fnum=normal.multiply();
result=fnum;
}
// /
private void div() {
lnum=Double.parseDouble(sb.toString());
normal=new Normal(fnum,lnum);
fnum=normal.divide();
result=fnum;
}
//%
private void sur() {
lnum=Double.parseDouble(sb.toString());
normal=new Normal(fnum,lnum);
fnum=normal.surpuls();
result=fnum;
}
// =
private void same(){
if(sign.equals("+")){
sum();
}
if(sign.equals("-")){
sub();
}
if(sign.equals("*")){
mul();
}
if(sign.equals("/")){
div();
}
if(sign.equals("%")){
sur();
}
}
//result
public void Result(){
if(result%1!=0)
jl.setText(""+result);
else
{
int i=(int)result;
jl.setText(""+i);
}
}
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println(sb.toString());
// 1~9
for(int i=0;i9;i++){
if(e.getSource()==jb[i]!sb.toString().equals("0")){
sb.append(jb[i].getText());
jl.setText(sb.toString());
}
else if(e.getSource()==jb[i]sb.toString().equals("0")){
int d=sb.length();
sb.delete(0, d);
sb.append(jb[i].getText());
jl.setText(sb.toString());
}
}
// 0
if(e.getSource()==jb[10]!sb.toString().equals("0")){
sb.append(jb[10].getText());
jl.setText(sb.toString());
}
// .
if(e.getSource()==jb[9]dot==0!sb.toString().equals("")){
dot++;
sb.append(jb[9].getText());
jl.setText(sb.toString());
}
// =
if(e.getSource()==jb[11]!sb.toString().equals("")){
same();
Result();
int d=sb.length();
sb.delete(0, d);
dot=0;
}
// +
if(e.getSource()==jbs!sb.toString().equals("")){
if(sign!="+"sign!=null)
same();
else
sum();
sign ="+";
Result();
int d=sb.length();
sb.delete(0, d);
dot=0;
}
//-
if(e.getSource()==jbo!sb.toString().equals("")){
if(fnum==0)
fnum=2*Double.parseDouble(sb.toString());
if(sign!="-"sign!=null)
same();
else
sub();
sign ="-";
Result();
int d=sb.length();
sb.delete(0, d);
dot=0;
}
//*
if(e.getSource()==jba!sb.toString().equals("")){
if(fnum==0)
fnum=1;
if(sign!="*"sign!=null)
same();
else
mul();
sign ="*";
Result();
int d=sb.length();
sb.delete(0, d);
dot=0;
}
// /
if(e.getSource()==jbb!sb.toString().equals("")){
if(fnum==0)
fnum=Math.pow(Double.parseDouble(sb.toString()),2);
if(sign!="/"sign!=null)
same();
else
div();
sign ="/";
Result();
int d=sb.length();
sb.delete(0, d);
dot=0;
}
//%
// if(e.getSource()==jby!sb.toString().equals("")){
// if(fnum==0){
// fnum=Double.parseDouble(sb.toString());
// result=fnum;
// }
// else {
// if(sign!="%"sign!=null)
// same();
// else{
// lnum=Double.parseDouble(sb.toString());
// normal=new Normal(fnum,lnum);
// fnum=normal.surpuls();
// result=fnum;
// }
// }
// sign ="%";
// Result();
// int d=sb.length();
// sb.delete(0, d);
// dot=0;
// }
//clear
if(e.getSource()==jbc){
int d=sb.length();
sb.delete(0, d);
jl.setText("0");
dot=0;
fnum=0;
lnum=0;
sign=null;
}
}
}
class viewScientific extends viewNormal{
public viewScientific(String title){
super(title);
setBounds(200,200,800,500);
}
}
//等號以后輸入符號用不了, String轉(zhuǎn) double 本來就有錯誤,你可以用我的擴(kuò)展成科學(xué)型的。
import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.TitledBorder; //導(dǎo)包 public class Jisuanqi extends JFrame implements ActionListener { //繼承JFrame 實(shí)現(xiàn)事件監(jiān)聽 private JTextField reasult; private JButton btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnAC, btnAdd, btnSub, btnReasult, btnD, btnAbout, btnCancel; private boolean add, sub, end, s, c; private String str; private double num1, num2; public Jisuanqi() { //構(gòu)造屬性 JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); JPanel p3 = new JPanel(); TitledBorder tb = new TitledBorder("輸出"); tb.setTitleColor(Color.BLUE); //標(biāo)題邊框底端線 設(shè)置顏色 btnAbout = new JButton(" 關(guān)于 "); btnCancel = new JButton("Cancel"); //兩個按鈕 btnCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { System.exit(0); } }); //給Cancel添加事件監(jiān)聽 當(dāng)鼠標(biāo)點(diǎn)擊時(shí) 程序結(jié)束 btnAbout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { JOptionPane.showMessageDialog(null, "黃蓋?。?, "消息", JOptionPane.INFORMATION_MESSAGE); } //給“關(guān)于”添加事件監(jiān)聽 當(dāng)鼠標(biāo)點(diǎn)擊時(shí) 彈出對話框 顯示黃蓋 }); p3.add(btnAbout); p3.add(btnCancel); // JPanel p4=new JPanel(); // JPanel p5=new JPanel(); // reasult.setBorder(tb); reasult = new JTextField("0", 20); reasult.setEditable(false); //設(shè)置不能修改 reasult.setHorizontalAlignment(JTextField.RIGHT); // 設(shè)置文本的水平對齊方式。 reasult.setForeground(Color.BLUE); //顏色 p1.setBorder(tb); p1.add(reasult); btn0 = new JButton("0"); btn0.addActionListener(this); btn1 = new JButton("1"); btn1.addActionListener(this); btn2 = new JButton("2"); btn2.addActionListener(this); btn3 = new JButton("3"); btn3.addActionListener(this); btn4 = new JButton("4"); btn4.addActionListener(this); btn5 = new JButton("5"); btn5.addActionListener(this); btn6 = new JButton("6"); btn6.addActionListener(this); btn7 = new JButton("7"); btn7.addActionListener(this); btn8 = new JButton("8"); btn8.addActionListener(this); btn9 = new JButton("9"); btn9.addActionListener(this); btnD = new JButton("."); btnD.addActionListener(this); btnD.setForeground(Color.RED); btnAC = new JButton("AC"); btnAC.addActionListener(this); btnAC.setBackground(Color.PINK); btnAdd = new JButton("+"); btnAdd.addActionListener(this); btnAdd.setForeground(Color.BLUE); btnSub = new JButton("—"); btnSub.addActionListener(this); btnSub.setForeground(Color.BLUE); btnReasult = new JButton("="); btnReasult.addActionListener(this); btnReasult.setForeground(Color.RED); //事件監(jiān)聽 + 顏色 p2.add(btn1); p2.add(btn2); p2.add(btn3); p2.add(btn4); p2.add(btn5); p2.add(btn6); p2.add(btn7); p2.add(btn8); p2.add(btn9); p2.add(btn0); p2.add(btnD); p2.add(btnAC); p2.add(btnAdd); p2.add(btnSub); p2.add(btnReasult); //面板上添加按鈕 p2.setLayout(new GridLayout(5, 3)); //面板上設(shè)置對齊方式 add(p1, BorderLayout.NORTH); add(p2, BorderLayout.CENTER); add(p3, BorderLayout.SOUTH); //將p1 p2 p3 面板對象添加到JFrame } public void num(int i) { String s = null; s = String.valueOf(i); if (end) { // 如果數(shù)字輸入結(jié)束,則將文本框置零,重新輸入 reasult.setText("0"); end = false; } if ((reasult.getText()).equals("0")) { // 如果文本框的內(nèi)容為零,則覆蓋文本框的內(nèi)容 reasult.setText(s); } else { // 如果文本框的內(nèi)容不為零,則在內(nèi)容后面添加數(shù)字 str = reasult.getText() + s; reasult.setText(str); } }/* * * String s=null; * * s=String.valueOf(i); * * str=reasult.getText()+s; * * reasult.setText(str); * * } */ public void actionPerformed(ActionEvent e) { if (e.getSource() == btn1) num(1); else if (e.getSource() == btn2) num(2); else if (e.getSource() == btn3) num(3); else if (e.getSource() == btn4) num(4); else if (e.getSource() == btn5) num(5); else if (e.getSource() == btn6) num(6); else if (e.getSource() == btn7) num(7); else if (e.getSource() == btn8) num(8); else if (e.getSource() == btn9) num(9); else if (e.getSource() == btn0) num(0); else if (e.getSource() == btnAdd) { sign(1); btnD.setEnabled(true); } else if (e.getSource() == btnSub) { sign(2); btnD.setEnabled(true); } else if (e.getSource() == btnAC) { btnD.setEnabled(true); reasult.setText("0"); } else if (e.getSource() == btnD) { str = reasult.getText(); str += "."; reasult.setText(str); btnD.setEnabled(false); } else if (e.getSource() == btnReasult) { btnD.setEnabled(true); num2 = Double.parseDouble(reasult.getText()); if (add) { num1 = num1 + num2; } else if (sub) { num1 = num1 - num2; } reasult.setText(String.valueOf(num1)); end = true; } } public void sign(int s) { if (s == 1) { add = true; sub = false; } else if (s == 2) { add = false; sub = true; } num1 = Double.parseDouble(reasult.getText()); end = true; } //設(shè)計(jì)計(jì)算的過程 public static void main(String[] args) { Jisuanqi j = new Jisuanqi(); j.setTitle("+/-簡易計(jì)算器"); j.setLocation(500, 280); j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //默認(rèn)關(guān)閉可以關(guān)閉程序 j.setResizable(false); j.pack(); j.setVisible(true); } } 這個計(jì)算機(jī),絕對讓你滿意