具體代碼如下:
公司主營業(yè)務:成都網(wǎng)站設(shè)計、成都做網(wǎng)站、移動網(wǎng)站開發(fā)等業(yè)務。幫助企業(yè)客戶真正實現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。創(chuàng)新互聯(lián)公司是一支青春激揚、勤奮敬業(yè)、活力青春激揚、勤奮敬業(yè)、活力澎湃、和諧高效的團隊。公司秉承以“開放、自由、嚴謹、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團隊有機會用頭腦與智慧不斷的給客戶帶來驚喜。創(chuàng)新互聯(lián)公司推出興海免費做網(wǎng)站回饋大家。
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Calculator ?extends JFrame implements ActionListener ?{
private JFrame jf;
private JButton[] allButtons;
private JButton clearButton;
private JTextField jtf;
public Calculator() {
//對圖形組件實例化
jf=new JFrame("任靜的計算器1.0:JAVA版");
jf.addWindowListener(new WindowAdapter(){
public void windowClosing(){
System.exit(0);
}
});
allButtons=new JButton[16];
clearButton=new JButton("清除");
jtf=new JTextField(25);
jtf.setEditable(false);
String str="123+456-789*0.=/";
for(int i=0;iallButtons.length;i++){
allButtons[i]=new JButton(str.substring(i,i+1));
}
}
public void init(){
//完成布局
jf.setLayout(new BorderLayout());
JPanel northPanel=new JPanel();
JPanel centerPanel=new JPanel();
JPanel southPanel=new JPanel();
northPanel.setLayout(new FlowLayout());
centerPanel.setLayout(new GridLayout(4,4));
southPanel.setLayout(new FlowLayout());
northPanel.add(jtf);
for(int i=0;i16;i++){
centerPanel.add(allButtons[i]);
}
southPanel.add(clearButton);
jf.add(northPanel,BorderLayout.NORTH);
jf.add(centerPanel,BorderLayout.CENTER);
jf.add(southPanel,BorderLayout.SOUTH);
addEventHandler();
}
//添加事件監(jiān)聽
public void addEventHandler(){
jtf.addActionListener(this);
for(int i=0;iallButtons.length;i++){
allButtons[i].addActionListener(this);
}
clearButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Calculator.this.jtf.setText("");
}
});
}
//事件處理
public void actionPerformed(ActionEvent e) {
//在這里完成事件處理 ?使計算器可以運行
String action=e.getActionCommand();
if(action=="+"||action=="-"||action=="*"||action=="/"){
}
}
public void setFontAndColor(){
Font f=new Font("宋體",Font.BOLD,24);
jtf.setFont(f);
jtf.setBackground(new Color(0x8f,0xa0,0xfb));
for(int i=0;i16;i++){
allButtons[i].setFont(f);
allButtons[i].setForeground(Color.RED);
}
}
public void showMe(){
init();
setFontAndColor();
jf.pack();
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args){
new Calculator().showMe();
}
}
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.ImageIcon;
import?javax.swing.JButton;
import?javax.swing.JFrame;
import?javax.swing.JPanel;
import?javax.swing.JTextField;
import?javax.swing.SwingConstants;
public?class?Jisuanqi?extends?JFrame?implements?ActionListener?{
/**
?*
?*/
private?static?final?long?serialVersionUID?=?1L;
Result?result?=?new?Result();?//?定義text的面板
Number_Key?number_key?=?new?Number_Key();?//?定義按鈕面板
//?當點擊按鈕+、-、*、/時,com?=?true
boolean?com?=?false;
//?當i=0時說明是我們第一次輸入,字符串text不會累加
int?i?=?0;
//?存放text的內(nèi)容
String?text?=?"";
//?存放點擊按鈕+、-、*、/之前的數(shù)值
double?defbutton?=?0;
//?+、-、*、/的代號分別為1,2,3,4
int?symbol?=?0;
//?構(gòu)造函數(shù)
Jisuanqi()?{
super("WangJiao");?//?設(shè)定標題
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);?//?設(shè)定關(guān)閉窗體時退出程序
JPanel?pane?=?new?JPanel();?//?定義主面板
pane.setLayout(new?BorderLayout());
setBounds(380,?220,?30,?80);?//?前兩個參數(shù)是在屏幕上顯示的坐標,后兩個是大小
//?替換圖標
ImageIcon?icon?=?new?ImageIcon("F:1.GIF");
//?Jisuanqi.class.getResource("APPLE.GIF")
//?);
setIconImage(icon.getImage());
pane.add(result,?BorderLayout.NORTH);
pane.add(number_key,?BorderLayout.CENTER);
pane.add(number_key.equal,?BorderLayout.SOUTH);
number_key.one.addActionListener(this);?//?對1按鈕添加監(jiān)聽事件
number_key.two.addActionListener(this);?//?對2按鈕添加監(jiān)聽事件
number_key.three.addActionListener(this);?//?對3按鈕添加監(jiān)聽事件
number_key.four.addActionListener(this);?//?對4按鈕添加監(jiān)聽事件
number_key.five.addActionListener(this);?//?對5按鈕添加監(jiān)聽事件
number_key.six.addActionListener(this);?//?對6按鈕添加監(jiān)聽事件
number_key.seven.addActionListener(this);?//?對7按鈕添加監(jiān)聽事件
number_key.eight.addActionListener(this);?//?對8按鈕添加監(jiān)聽事件
number_key.nine.addActionListener(this);?//?對9按鈕添加監(jiān)聽事件
number_key.zero.addActionListener(this);?//?對0按鈕添加監(jiān)聽事件
number_key.ce.addActionListener(this);?//?對置零按鈕添加監(jiān)聽事件
number_key.plus.addActionListener(this);?//?對+按鈕添加監(jiān)聽事件
number_key.equal.addActionListener(this);?//?對=按鈕添加監(jiān)聽事件
number_key.sub.addActionListener(this);?//?對-按鈕添加監(jiān)聽事件
number_key.mul.addActionListener(this);?//?對*按鈕添加監(jiān)聽事件
number_key.div.addActionListener(this);?//?對/按鈕添加監(jiān)聽事件
number_key.point.addActionListener(this);?//?對.按鈕添加監(jiān)聽事件
setContentPane(pane);
pack();?//?初始化窗體大小為正好盛放所有按鈕
}
//?各個按鈕觸發(fā)的事件
public?void?actionPerformed(ActionEvent?e)?{
/*
?*?如果是點擊數(shù)字按鈕那么先要判斷是否在此之前點擊了+、-、*、/、=,如果是那么com=true?如果沒有com=
?*?false;或者是否點擊數(shù)字鍵,如果是i?=?1,如果沒有?i?=?0;
?*/
if?(e.getSource()?==?number_key.one)?{
if?(com?||?i?==?0)?{
result.text.setText("1");
com?=?false;
i?=?1;
}?else?{
text?=?result.text.getText();
result.text.setText(text?+?"1");
}
}?else?if?(e.getSource()?==?number_key.two)?{
if?(com?||?i?==?0)?{
result.text.setText("2");
com?=?false;
i?=?1;
}?else?{
text?=?result.text.getText();
result.text.setText(text?+?"2");
}
}?else?if?(e.getSource()?==?number_key.three)?{
if?(com?||?i?==?0)?{
result.text.setText("3");
com?=?false;
i?=?1;
}?else?{
text?=?result.text.getText();
result.text.setText(text?+?"3");
}
}?else?if?(e.getSource()?==?number_key.four)?{
if?(com?||?i?==?0)?{
result.text.setText("4");
com?=?false;
i?=?1;
}?else?{
text?=?result.text.getText();
result.text.setText(text?+?"4");
}
}?else?if?(e.getSource()?==?number_key.five)?{
if?(com?||?i?==?0)?{
result.text.setText("5");
com?=?false;
i?=?1;
}?else?{
text?=?result.text.getText();
result.text.setText(text?+?"5");
}
}?else?if?(e.getSource()?==?number_key.six)?{
if?(com?||?i?==?0)?{
result.text.setText("6");
com?=?false;
i?=?1;
}?else?{
text?=?result.text.getText();
result.text.setText(text?+?"6");
}
}?else?if?(e.getSource()?==?number_key.seven)?{
if?(com?||?i?==?0)?{
result.text.setText("7");
com?=?false;
i?=?1;
}?else?{
text?=?result.text.getText();
result.text.setText(text?+?"7");
}
}?else?if?(e.getSource()?==?number_key.eight)?{
if?(com?||?i?==?0)?{
result.text.setText("8");
com?=?false;
i?=?1;
}?else?{
text?=?result.text.getText();
result.text.setText(text?+?"8");
}
}?else?if?(e.getSource()?==?number_key.nine)?{
if?(com?||?i?==?0)?{
result.text.setText("9");
com?=?false;
i?=?1;
}?else?{
text?=?result.text.getText();
result.text.setText(text?+?"9");
}
}
/*
?*?對于0這個按鈕有一定的說法,在我的程序里不會出現(xiàn)如00000這樣的情況,我加了判斷條件就是
?*?如果text中的數(shù)值=0就要判斷在這個數(shù)值中是否有.存在?如果有那么就在原來數(shù)值基礎(chǔ)之上添?加0;否則保持原來的數(shù)值不變
?*/
else?if?(e.getSource()?==?number_key.zero)?{?//?result.text.getText()是得到text里內(nèi)容的意思
if?(com?||?i?==?0)?{
result.text.setText("0");
com?=?false;
i?=?1;
}?else?{
text?=?result.text.getText();
if?(Float.parseFloat(text)??0?||?Float.parseFloat(text)??0)?{?//?Float.parseFloat(text)就是類型轉(zhuǎn)換了,下面都是一樣
result.text.setText(text?+?"0");
}?else?{
if?(text.trim().indexOf(".")?==?-1)?{
result.text.setText(text);
}?else?{
result.text.setText(text?+?"0");
}
}
}
}?else?if?(e.getSource()?==?number_key.ce)?{
result.text.setText("0");
i?=?0;
com?=?true;
//?text?=?"";
defbutton?=?0;
}
/*
?*?本程序不會讓一個數(shù)值中出現(xiàn)2個以上的小數(shù)點.具體做法是:判斷是否已經(jīng)存在.存在就不添加,?不存在就添加.
?*/
else?if?(e.getSource()?==?number_key.point)?{
if?(com?||?i?==?0)?{
result.text.setText("0.");
com?=?false;
i?=?1;
}?else?{
text?=?result.text.getText();
if?(text.trim().indexOf(".")?==?-1)?{
result.text.setText(text?+?".");
}?else?{
result.text.setText(text);
}
}
}?//?獲得點擊+之前的數(shù)值
else?if?(e.getSource()?==?number_key.plus)?{
com?=?true;
i?=?0;
defbutton?=?Double.parseDouble(result.text.getText());
symbol?=?1;
}?//?獲得點擊-之前的數(shù)值
else?if?(e.getSource()?==?number_key.sub)?{
com?=?true;
i?=?0;
defbutton?=?Double.parseDouble(result.text.getText());
symbol?=?2;
}?//?獲得點擊*之前的數(shù)值
else?if?(e.getSource()?==?number_key.mul)?{
com?=?true;
i?=?0;
defbutton?=?Double.parseDouble(result.text.getText());
System.out.println(defbutton);
symbol?=?3;
}?//?獲得點擊/之前的數(shù)值
else?if?(e.getSource()?==?number_key.div)?{
com?=?true;
i?=?0;
defbutton?=?Double.parseDouble(result.text.getText());
symbol?=?4;
}?else?if?(e.getSource()?==?number_key.equal)?{
switch?(symbol)?{
case?1:?{?//?計算加法
double?ad?=?defbutton
+?Double.parseDouble(result.text.getText());
result.text.setText(ad?+?"");
i?=?0;
text?=?"";
break;
}
case?2:?{?//?計算減法
double?ad?=?defbutton
-?Double.parseDouble(result.text.getText());
result.text.setText(String.valueOf(ad));
i?=?0;
text?=?"";
break;
}
case?3:?{?//?計算乘法
double?ad?=?defbutton
*?Double.parseDouble(result.text.getText());
result.text.setText(ad?+?"");
i?=?0;
text?=?"";
break;
}
case?4:?{?//?計算除法
double?ad?=?defbutton
/?Double.parseDouble(result.text.getText());
result.text.setText(ad?+?"");
i?=?0;
text?=?"";
break;
}
}
System.out.println(com);
}
System.out.println(result.text.getText());
}
@SuppressWarnings("deprecation")
public?static?void?main(String[]?args)?{
Jisuanqi?loveyou?=?new?Jisuanqi();
loveyou.show();
}
}
//?計算器數(shù)字按鈕定義面板
class?Number_Key?extends?JPanel?{
/**
?*
?*/
private?static?final?long?serialVersionUID?=?1L;
JButton?zero?=?new?JButton("0");?//?數(shù)字鍵0
JButton?one?=?new?JButton("1");?//?數(shù)字鍵1
JButton?two?=?new?JButton("2");?//?數(shù)字鍵2
JButton?three?=?new?JButton("3");?//?數(shù)字鍵3
JButton?four?=?new?JButton("4");?//?數(shù)字鍵4
JButton?five?=?new?JButton("5");?//?數(shù)字鍵5
JButton?six?=?new?JButton("6");?//?數(shù)字鍵6
JButton?seven?=?new?JButton("7");?//?數(shù)字鍵7
JButton?eight?=?new?JButton("8");?//?數(shù)字鍵8
JButton?nine?=?new?JButton("9");?//?數(shù)字鍵9
JButton?plus?=?new?JButton("+");
JButton?sub?=?new?JButton("-");
JButton?mul?=?new?JButton("*");
JButton?div?=?new?JButton("/");
JButton?equal?=?new?JButton("=");
JButton?ce?=?new?JButton("清零");?//?置零鍵
JButton?point?=?new?JButton(".");
Number_Key()?{
setLayout(new?GridLayout(4,?4,?1,?1));?//?定義布局管理器為網(wǎng)格布局
setBackground(Color.blue);?//?設(shè)置背景顏色
//?添加按鈕
add(one);
add(two);
add(three);
add(four);
add(five);
add(six);
add(seven);
add(eight);
add(nine);
add(zero);
add(plus);
add(sub);
add(mul);
add(div);
add(point);
add(equal);
add(ce);
}
}
//?計算器顯示結(jié)果的窗體
class?Result?extends?JPanel?{
/**
?*
?*/
private?static?final?long?serialVersionUID?=?1L;
//?text先是輸入和結(jié)果
JTextField?text?=?new?JTextField("0");
@SuppressWarnings("deprecation")
Result()?{?//?講輸入的數(shù)字或得到的結(jié)果在text的右邊顯示
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.enable(false);?//?文本框不能編輯
setLayout(new?BorderLayout());?//?設(shè)定布局管理器邊框布局
add(text,?BorderLayout.CENTER);?//?text放置在窗體的中間
}
}
直接復制?保存成Jisuanqi?.java可以直接運行了
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; //導包 public class Jisuanqi extends JFrame implements ActionListener { //繼承JFrame 實現(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); //標題邊框底端線 設(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)聽 當鼠標點擊時 程序結(jié)束 btnAbout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { JOptionPane.showMessageDialog(null, "黃蓋??!", "消息", JOptionPane.INFORMATION_MESSAGE); } //給“關(guān)于”添加事件監(jiān)聽 當鼠標點擊時 彈出對話框 顯示黃蓋 }); 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è)計計算的過程 public static void main(String[] args) { Jisuanqi j = new Jisuanqi(); j.setTitle("+/-簡易計算器"); j.setLocation(500, 280); j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //默認關(guān)閉可以關(guān)閉程序 j.setResizable(false); j.pack(); j.setVisible(true); } } 這個計算機,絕對讓你滿意
簡單寫了下,代碼如下請參照:
/**
*?計算器類
*?
*?@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;
//?運算結(jié)果
private?double?resultNum?=?0.0;
//?運算符
private?String?operator?=?"=";
public?Calculator(String?title)?{
//?設(shè)置標題欄
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);?//?不允許按鈕定位焦點
}
/*?將文本框與按鈕添加到窗體中?*/
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ù)點
handleNumber(text);
}?else?if?("+-*/=".indexOf(text)?!=?-1)?{?//?運算符
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ù)點
handleNumber(text);
}?else?{?//?處理運算符
handleOperator(text);
}
}
/**
*?處理數(shù)字和小數(shù)點
*?
*?@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;
}
/**
*?處理運算符
*?
*?@param?text
*/
private?void?handleOperator(String?text)?{
switch?(operator)?{?//?處理各項運算??適用于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;
}
//?將文本框的值修改為運算結(jié)果
this.result.setText(String.valueOf(resultNum));
//?將點擊的運算符放入operator保存
operator?=?text;
//?下一個數(shù)字第一次點擊
isFirstDigit?=?true;
}
public?static?void?main(String[]?args)?{
?new?Calculator("My?Calculator");
?}
}
運行結(jié)果如下:
/*
* @(#)JCalculator.java 1.00 06/17/2015
*/
import?java.awt.*;
import?java.awt.event.*;
import?javax.swing.*;
/**
* A simple calculator program.
*?pI saw this program in a QQ group, and help a friend correct it./p
*
*?@author?Singyuen?Yip
*?@version?1.00 12/29/2009
*?@see?JFrame
*?@see?ActionListener
*/
public?class?JCalculator?extends?JFrame?implements?ActionListener {
/**
* Serial Version UID
*/
private?static?final?long?serialVersionUID?= -169068472193786457L;
/**
* This class help close the Window.
*?@author?Singyuen?Yip
*
*/
private?class?WindowCloser?extends?WindowAdapter {
public?void?windowClosing(WindowEvent we) {
System.exit(0);
}
}
int?i;
// Strings for Digit Operator buttons.
private?final?String[]?str?= {?"7",?"8",?"9",?"/",?"4",?"5",?"6",?"*","1",
"2",?"3",?"-",?".",?"0",?"=",?"+"?};
// Build buttons.
JButton[]?buttons?=?new?JButton[str.length];
// For cancel or reset.
JButton?reset?=?new?JButton("CE");
// Build the text field to show the result.
JTextField?display?=?new?JTextField("0");
/**
* Constructor without parameters.
*/
public?JCalculator() {
super("Calculator");
// Add a panel.
JPanel panel1 =?new?JPanel(new?GridLayout(4, 4));
// panel1.setLayout(new GridLayout(4,4));
for?(i?= 0;?i??str.length;?i++) {
buttons[i] =?new?JButton(str[i]);
panel1.add(buttons[i]);
}
JPanel panel2 =?new?JPanel(new?BorderLayout());
// panel2.setLayout(new BorderLayout());
panel2.add("Center",?display);
panel2.add("East",?reset);
// JPanel panel3 = new Panel();
getContentPane().setLayout(new?BorderLayout());
getContentPane().add("North", panel2);
getContentPane().add("Center", panel1);
// Add action listener for each digit operator button.
for?(i?= 0;?i??str.length;?i++)
buttons[i].addActionListener(this);
// Add listener for "reset" button.
reset.addActionListener(this);
// Add listener for "display" button.
display.addActionListener(this);
// The "close" button "X".
addWindowListener(new?WindowCloser());
// Initialize the window size.
setSize(800, 800);
// Show the window.
// show(); Using show() while JDK version is below 1.5.
setVisible(true);
// Fit the certain size.
pack();
}
public?void?actionPerformed(ActionEvent e) {
Object target = e.getSource();
String label = e.getActionCommand();
if?(target ==?reset)
handleReset();
else?if?("0123456789.".indexOf(label) 0)
handleNumber(label);
else
handleOperator(label);
}
// Is the first digit pressed?
boolean?isFirstDigit?=?true;
/**
* Number handling.
*?@param?key the key of the button.
*/
public?void?handleNumber(String key) {
if?(isFirstDigit)
display.setText(key);
else?if?((key.equals(".")) (display.getText().indexOf(".") 0))
display.setText(display.getText() +?".");
else?if?(!key.equals("."))
display.setText(display.getText() + key);
isFirstDigit?=?false;
}
/**
* Reset the calculator.
*/
public?void?handleReset() {
display.setText("0");
isFirstDigit?=?true;
operator?=?"=";
}
double?number?= 0.0;
String?operator?=?"=";
/**
* Handling the operation.
*?@param?key pressed operator's key.
*/
public?void?handleOperator(String key) {
if?(operator.equals("+"))
number?+= Double.valueOf(display.getText());
else?if?(operator.equals("-"))
number?-= Double.valueOf(display.getText());
else?if?(operator.equals("*"))
number?*= Double.valueOf(display.getText());
else?if?(operator.equals("/"))
number?/= Double.valueOf(display.getText());
else?if?(operator.equals("="))
number?= Double.valueOf(display.getText());
display.setText(String.valueOf(number));
operator?= key;
isFirstDigit?=?true;
}
public?static?void?main(String[] args) {
new?JCalculator();
}
}
運行界面: