① java設計一個簡易計算器:類名為Calculator 具有「加,減,乘,除,和求余」的功能(使用控制台輸出即可
給你個思路吧。。 還有就後期改下。。
這個用swing 弄的。。 你看下希望可以幫到你。 。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Compute extends JFrame implements ActionListener
{
JButton[] btn;
JLabel lab;
JTextField text;
String s1,s2,s;
Compute(String str)
{
super(str);
lab=new JLabel("計算結果");
text=new JTextField(13);
text.setHorizontalAlignment(JTextField.RIGHT);
text.setEditable(false);//禁止文本框輸入
text.setForeground(Color.red);
btn=new JButton[8];
for(int i=0;i<4;i++)
{
btn[i]=new JButton((i+1)+"");
}
btn[4]=new JButton("+");
btn[5]=new JButton("-");
btn[6]=new JButton("=");
btn[7]=new JButton("清空");
this.setLayout(new FlowLayout());
this.add(lab);
this.add(text);
for(int i=0;i<8;i++)
{
this.add(btn[i]);
btn[i].addActionListener(this);
}
this.setBounds(200,200,230,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.show();
}
public void actionPerformed(ActionEvent event)
{
String str=event.getActionCommand();
if(str.equals("清空"))
{
text.setText("");
}else if(str.equals("1"))
{
text.setText(text.getText()+"1");//在文本框以追加的形式顯示1
}else if(str.equals("2"))
{
text.setText(text.getText()+"2");//在文本框以追加的形式顯示2
}else if(str.equals("3"))
{
text.setText(text.getText()+"3");//在文本框以追加的形式顯示3
}else if(str.equals("4"))
{
text.setText(text.getText()+"4");//在文本框以追加的形式顯示4
}else if(str.equals("+"))
{
s1=text.getText(); //將文本框的內容賦給s1
s="+"; //將+賦給s
text.setText(""); //將文本框清空
}else if(str.equals("-"))
{
s1=text.getText(); //將文本框的內容賦給s1
s="-"; //將-賦給s
text.setText(""); //將文本框清空
}else if(str.equals("="))
{
s2=text.getText();
double d1=Double.parseDouble(s1);
double d2=Double.parseDouble(s2);
double d=0;
if(s.equals("+"))
{
d=d1+d2;
}else if(s.equals("-"))
{
d=d1-d2;
}
text.setText(d+"");//將計算結果放到文本框中
}
}
public static void main(String[] args)
{
Compute c=new Compute("計算器");
}
}
② 用JAVA編寫一個簡單的計算器,要求如下
以下是上圖計算器的代碼:
packageComputer;
importjava.awt.BorderLayout;
importjava.awt.Color;
importjava.awt.Container;
importjava.awt.Font;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.util.Stack;
importjavax.swing.JApplet;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
{
/**
*
*/
=1L;
privateJTextFieldtextField=newJTextField("請輸入");
Stringoperator="";//操作
Stringinput="";//輸入的式子
booleanflag=true;
//booleanflag1=true;
//booleanflag2=true;
publicvoidinit()//覆寫Applet里邊的init方法
{
ContainerC=getContentPane();
JButtonb[]=newJButton[16];
JPanelpanel=newJPanel();
C.add(textField,BorderLayout.NORTH);
C.add(panel,BorderLayout.CENTER);
panel.setLayout(newGridLayout(4,4,5,5));
Stringname[]={"7","8","9","+","4","5","6","-","1","2","3","*","0","C","=","/"};//設置按鈕
for(inti=0;i<16;i++)//添加按鈕
{
b[i]=newJButton(name[i]);
b[i].setBackground(newColor(192,192,192));
b[i].setForeground(Color.BLUE);//數字鍵設置為藍顏色
if(i%4==3)
b[i].setForeground(Color.RED);
b[i].setFont(newFont("宋體",Font.PLAIN,16));//設置字體格式
panel.add(b[i]);
b[i].addActionListener(this);
}
b[13].setForeground(Color.RED);//非數字鍵,即運算鍵設置為紅顏色
b[13].setForeground(Color.RED);
}
publicvoidactionPerformed(ActionEvente)
{
intcnt=0;
StringactionCommand=e.getActionCommand();
if(actionCommand.equals("+")||actionCommand.equals("-")||actionCommand.equals("*")||actionCommand.equals("/"))
input+=""+actionCommand+"";//設置輸入,把輸入的樣式改成需要的樣子
elseif(actionCommand.equals("C"))
input="";
elseif(actionCommand.equals("="))//當監聽到等號時,則處理input
{
input+="="+compute(input);
textField.setText(input);
input="";
cnt=1;
}
else
input+=actionCommand;//數字為了避免多位數的輸入不需要加空格
if(cnt==0)
textField.setText(input);
}
privateStringcompute(Stringinput)//即1237的樣例
{
Stringstr[];
str=input.split("");
Stack<Double>s=newStack<Double>();
doublem=Double.parseDouble(str[0]);
s.push(m);
for(inti=1;i<str.length;i++)
{
if(i%2==1)
{
if(str[i].compareTo("+")==0)
{
doublehelp=Double.parseDouble(str[i+1]);
s.push(help);
}
if(str[i].compareTo("-")==0)
{
doublehelp=Double.parseDouble(str[i+1]);
s.push(-help);
}
if(str[i].compareTo("*")==0)
{
doublehelp=Double.parseDouble(str[i+1]);
doubleans=s.peek();//取出棧頂元素
s.pop();//消棧
ans*=help;
s.push(ans);
}
if(str[i].compareTo("/")==0)
{
doublehelp=Double.parseDouble(str[i+1]);
doubleans=s.peek();
s.pop();
ans/=help;
s.push(ans);
}
}
}
doubleans=0d;
while(!s.isEmpty())
{
ans+=s.peek();
s.pop();
}
Stringresult=String.valueOf(ans);
returnresult;
}
publicstaticvoidmain(Stringargs[])
{
JFrameframe=newJFrame("Count");
Countapplet=newCount();
frame.getContentPane().add(applet,BorderLayout.CENTER);
applet.init();//applet的init方法
applet.start();//線程開始
frame.setSize(350,400);//設置窗口大小
frame.setVisible(true);//設置窗口可見
}
}
③ java設計一個計算器
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class jisuanqi extends Applet implements ActionListener
{
double x=0;
double y=0;
double w;
int h=0;
TextField t=new TextField(15);
Button b1=new Button("1");
Button b2=new Button("2");
Button b3=new Button("3");
Button b4=new Button("4");
Button b5=new Button("5");
Button b6=new Button("6");
Button b7=new Button("7");
Button b8=new Button("8");
Button b9=new Button("9");
Button b0=new Button("0");
Button b10=new Button("+");
Button b11=new Button("-");
Button b12=new Button("*");
Button b13=new Button("/");
Button b14=new Button("C");
Button b15=new Button("=");
public void init()
{
setLayout(new BorderLayout());
add(t,"North");
Panel p1=new Panel();
add(p1,"Center");
p1.setLayout(new GridLayout(4,4,5,5));
p1.add(b1);
p1.add(b2);
p1.add(b3);
p1.add(b14);
p1.add(b4);
p1.add(b5);
p1.add(b6);
p1.add(b10);
p1.add(b7);
p1.add(b8);
p1.add(b9);
p1.add(b11);
p1.add(b0);
p1.add(b12);
p1.add(b13);
p1.add(b15);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b10.addActionListener(this);
b11.addActionListener(this);
b12.addActionListener(this);
b13.addActionListener(this);
b14.addActionListener(this);
b15.addActionListener(this);
b0.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String ts=e.getActionCommand();
char ysf=ts.charAt(0);
if(ts=="C") t.setText("");
else if(ts=="+")
{
x=Integer.parseInt(t.getText());
t.setText("");
h=1;
}
else if(ts=="-")
{
x=Integer.parseInt(t.getText());
t.setText("");
h=2;
}
else if(ts=="*")
{
x=Integer.parseInt(t.getText());
t.setText("");
h=3;
}
else if(ts=="/")
{
x=Integer.parseInt(t.getText());
t.setText("");
h=4;
}
else if(ts.equals("="))
{
y=Integer.parseInt(t.getText());
switch(h)
{
case 1:w = x+y; break;
case 2:w = x-y; break;
case 3:w = x*y; break;
case 4:w = x/y;
}
t.setText(String.valueOf(w));
}
else
{
t.setText(t.getText()+ts);
}
}
}
④ .設計一個簡單計算器,JAVA
以下是我按你的需求手寫的代碼,希望對你有所幫助,望採納
importjava.awt.*;
importjava.awt.event.*;
publicclassTestextendsFrame{
publicstaticvoidmain(Stringargs[]){
newTest();
}
TextFieldnumber1=newTextField();
TextFieldnumber2=newTextField();
TextFieldresult=newTextField();
Buttonplus=newButton("+");
Buttonsubtract=newButton("-");
Buttonmultiply=newButton("×");
Buttondivide=newButton("÷");
doublenum1,num2,resl;
Test(){
setLayout(null);
//關閉窗口
this.addWindowListener(newWindowAdapter(){
publicvoidwindowClosing(WindowEvente){
System.exit(0);
}
});
setBounds(200,100,400,300);
setTitle("簡單計算器");
//設置窗口是否可變大小
setResizable(false);
setVisible(true);
number1.setBounds(100,80,150,20);
add(number1);
number2.setBounds(100,130,150,20);
add(number2);
result.setBounds(100,180,150,20);
add(result);
plus.setBounds(300,55,80,20);
add(plus);
plus.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
if(number1.getText().trim()!=""&&number2.getText().trim()!=""){
num1=Double.parseDouble(number1.getText().trim());
num2=Double.parseDouble(number2.getText().trim());
resl=num1+num2;
result.setText(String.valueOf(resl));
number1.setText("");
number2.setText("");
}
}
});
subtract.setBounds(300,105,80,20);
add(subtract);
subtract.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
if(number1.getText().trim()!=""&&number2.getText().trim()!=""){
num1=Double.parseDouble(number1.getText().trim());
num2=Double.parseDouble(number2.getText().trim());
resl=num1-num2;
result.setText(String.valueOf(resl));
number1.setText("");
number2.setText("");
}
}
});
multiply.setBounds(300,155,80,20);
add(multiply);
multiply.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
if(number1.getText().trim()!=""&&number2.getText().trim()!=""){
num1=Double.parseDouble(number1.getText().trim());
num2=Double.parseDouble(number2.getText().trim());
resl=num1*num2;
result.setText(String.valueOf(resl));
number1.setText("");
number2.setText("");
}
}
});
divide.setBounds(300,205,80,20);
add(divide);
divide.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
if(number1.getText().trim()!=""&&number2.getText().trim()!=""){
num1=Double.parseDouble(number1.getText().trim());
num2=Double.parseDouble(number2.getText().trim());
resl=num1/num2;
result.setText(String.valueOf(resl));
number1.setText("");
number2.setText("");
}
}
});
}
publicvoidpaint(Graphicsg){
g.setColor(Color.LIGHT_GRAY);
g.fillRect(20,45,250,230);
g.setColor(Color.BLACK);
g.drawString("操作數",60,95);
g.drawString("操作數",60,145);
g.drawString("結果",70,195);
}
}
⑤ 用java編寫簡單計算器
這個是我以前寫的一個程序 我把里邊沒用的注掉了 如果你想添加其他功能 把注釋解開就行了
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame {
private Container container;
private GridBagLayout layout;
private GridBagConstraints constraints;
private JTextField displayField;// 計算結果顯示區
private String lastCommand;// 保存+,-,*,/,=命令
private double result;// 保存計算結果
private boolean start;// 判斷是否為數字的開始
public Calculator() {
super("Calculator");
container = getContentPane();
layout = new GridBagLayout();
container.setLayout(layout);
constraints = new GridBagConstraints();
start = true;
result = 0;
lastCommand = "=";
displayField = new JTextField(20);
displayField.setHorizontalAlignment(JTextField.RIGHT);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 4;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 100;
constraints.weighty = 100;
layout.setConstraints(displayField, constraints);
container.add(displayField);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
// addButton("Backspace", 0, 1, 2, 1, insert);
// addButton("CE", 2, 1, 1, 1, insert);
// addButton("C", 3, 1, 1, 1, insert);
addButton("7", 0, 2, 1, 1, insert);
addButton("8", 1, 2, 1, 1, insert);
addButton("9", 2, 2, 1, 1, insert);
addButton("/", 3, 2, 1, 1, command);
addButton("4", 0, 3, 1, 1, insert);
addButton("5", 1, 3, 1, 1, insert);
addButton("6", 2, 3, 1, 1, insert);
addButton("*", 3, 3, 1, 1, command);
addButton("1", 0, 4, 1, 1, insert);
addButton("2", 1, 4, 1, 1, insert);
addButton("3", 2, 4, 1, 1, insert);
addButton("-", 3, 4, 1, 1, command);
addButton("0", 0, 5, 1, 1, insert);
// addButton("+/-", 1, 5, 1, 1, insert);// 只顯示"-"號,"+"沒有實用價值
addButton(".", 2, 5, 1, 1, insert);
addButton("+", 3, 5, 1, 1, command);
addButton("=", 0, 6, 4, 1, command);
this.setResizable(false);
setSize(180, 200);
setVisible(true);
}
private void addButton(String label, int row, int column, int with,
int height, ActionListener listener) {
JButton button = new JButton(label);
constraints.gridx = row;
constraints.gridy = column;
constraints.gridwidth = with;
constraints.gridheight = height;
constraints.fill = GridBagConstraints.BOTH;
button.addActionListener(listener);
layout.setConstraints(button, constraints);
container.add(button);
}
private class InsertAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
if (start) {
displayField.setText("");
start = false;
if (input.equals("+/-"))
displayField.setText(displayField.getText() + "-");
}
if (!input.equals("+/-")) {
if (input.equals("Backspace")) {
String str = displayField.getText();
if (str.length() > 0)
displayField
.setText(str.substring(0, str.length() - 1));
} else if (input.equals("CE") || input.equals("C")) {
displayField.setText("0");
start = true;
} else
displayField.setText(displayField.getText() + input);
}
}
}
private class CommandAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
String command = evt.getActionCommand();
if (start) {
lastCommand = command;
} else {
calculate(Double.parseDouble(displayField.getText()));
lastCommand = command;
start = true;
}
}
}
public void calculate(double x) {
if (lastCommand.equals("+"))
result += x;
else if (lastCommand.equals("-"))
result -= x;
else if (lastCommand.equals("*"))
result *= x;
else if (lastCommand.equals("/"))
result /= x;
else if (lastCommand.equals("="))
result = x;
displayField.setText("" + result);
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
⑥ 用Java設計一個簡單的計算器。
無聊寫了個,修復了下Bug:
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JOptionPane;
importjavax.swing.JTextField;
{
=1L;
privateJButtonplus,rece,multiply,divice,reset;
privateJTextFieldone,two,result;
privatebooleandevice_falg=false;
privatefinalintwidth=400,height=300;
publicCalculate(){
super("修改密碼");
this.setLayout(null);
this.setSize(width,height);
init();
Layout();
}
publicvoidinit(){
plus=newJButton("加");
rece=newJButton("減");
multiply=newJButton("乘");
divice=newJButton("除");
reset=newJButton("清空");
one=newJTextField();
two=newJTextField();
result=newJTextField();
}
publicvoidLayout(){
this.add(newJLabel("第一個數")).setBounds(20,10,60,80);
this.add(one).setBounds(100,38,100,25);
this.add(newJLabel("第二個數")).setBounds(20,40,60,80);
this.add(two).setBounds(100,70,100,25);
this.add(newJLabel("結果")).setBounds(20,85,60,80);
this.add(result).setBounds(100,110,100,25);
this.add(plus).setBounds(70,170,80,25);
this.add(rece).setBounds(200,170,80,25);
this.add(multiply).setBounds(70,200,80,25);
this.add(divice).setBounds(200,200,80,25);
this.add(reset).setBounds(300,220,80,25);
plus.addActionListener(this);
rece.addActionListener(this);
multiply.addActionListener(this);
divice.addActionListener(this);
reset.addActionListener(this);
this.setVisible(true);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
publicbooleanFormat(){
booleanFLAG=false;
booleanflag=false;
Stringone=this.one.getText().toString().trim();
Stringtwo=this.two.getText().toString().trim();
if(one==null||one.equals("")||two==null||two.equals("")){
JOptionPane.showMessageDialog(getParent(),"請輸入完整信息!");
FLAG=false;
flag=true;
}
booleanboll_1=one.matches("[\d]{1,100}");
booleanboll_2=two.matches("[\d]{1,100}");
booleanboll_3=one.matches("[\d]{1,100}+[.]+[\d]{1,100}");
booleanboll_4=two.matches("[\d]{1,100}+[.]+[\d]{1,100}");
if(flag){
returnfalse;
}
if((boll_1&&boll_2)||(boll_3&&boll_4)||(boll_1&&boll_4)
||(boll_3&&boll_2)){
FLAG=true;
}else{
JOptionPane.showMessageDialog(getParent(),"請輸入數字!");
FLAG=false;
}
if(FLAG&&device_falg){
if(Double.parseDouble(two)==0){
JOptionPane.showMessageDialog(getParent(),"被除數不能為0!");
FLAG=false;
device_falg=false;
}
}
returnFLAG;
}
publicdoublePlus(doubleone,doubletwo){
returnone+two;
}
publicdoubleMultiply(doubleone,doubletwo){
returnone*two;
}
publicdoubleDivice(doubleone,doubletwo){
returnone/two;
}
publicdoubleRece(doubleone,doubletwo){
returnone-two;
}
publicvoidClear(){
one.setText("");
two.setText("");
result.setText("");
}
@Override
publicvoidactionPerformed(ActionEvente){
Objecto=e.getSource();
if(o==reset){
Clear();
return;
}
if(o==divice){
device_falg=true;
}
if(!Format()){
return;
}
doubleone=Double.parseDouble(this.one.getText());
doubletwo=Double.parseDouble(this.two.getText());
doubleresult=0;
if(o==plus){
result=Plus(one,two);
}elseif(o==rece){
result=Rece(one,two);
}elseif(o==multiply){
result=Multiply(one,two);
}elseif(o==divice){
result=Divice(one,two);
}
this.result.setText(""+result);
}
publicstaticvoidmain(String[]args){
newCalculate();
}
}
⑦ java設計個簡單計算器
packagezhang16;
importjava.awt.*;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.text.DecimalFormat;
importjavax.swing.*;
importjavax.swing.border.Border;
importjavax.swing.border.LineBorder;
publicclass簡單計算器16_4extendsJFrame{
privatedoublenum1,num2,res;
privateJTextFieldnumber1=newJTextField(5);
privateJTextFieldnumber2=newJTextField(5);
privateJTextFieldresult=newJTextField(10);
JButtonjia=newJButton("jia");
JButtonjian=newJButton("jian");
JButtoncheng=newJButton("cheng");
JButtonchu=newJButton("chu");
public簡單計算器16_4(){
//TODOAuto-generatedconstructorstub
JPanelp1=newJPanel();
JPanelp2=newJPanel();
setLayout(newGridLayout(2,1));
this.add(p1,newFlowLayout());
p1.add(newJLabel("num1"));
p1.add(number1);
p1.add(newJLabel("num"));
p1.add(number2);
p1.add(newJLabel("result"));
p1.add(result);
Borderb=newLineBorder(Color.black,1);
this.add(p2,newFlowLayout());
p2.add(jia);
p2.add(jian);
p2.add(cheng);
p2.add(chu);
p1.setBorder(b);
p2.setBorder(b);
ButtonListenerActionListener=newButtonListener();
jia.addActionListener(ActionListener);
jian.addActionListener(ActionListener);
cheng.addActionListener(ActionListener);
chu.addActionListener(ActionListener);
}
{
@Override
publicvoidactionPerformed(ActionEvente){
//TODOAuto-generatedmethodstub
DecimalFormatdf=newDecimalFormat("0.00");
if(e.getSource()==jia){
Stringnum11=number1.getText();
num1=Double.parseDouble(num11);
Stringnum22=number2.getText();
num2=Double.parseDouble(num22);
res=num1+num2;
result.setText(df.format(res)+"");
}elseif(e.getSource()==jian){
Stringnum11=number1.getText();
num1=Double.parseDouble(num11);
Stringnum22=number2.getText();
num2=Double.parseDouble(num22);
res=num1-num2;
result.setText(df.format(res)+"");
}elseif(e.getSource()==cheng){
Stringnum11=number1.getText();
num1=Double.parseDouble(num11);
Stringnum22=number2.getText();
num2=Double.parseDouble(num22);
res=num1*num2;
result.setText(df.format(res)+"");
}elseif(e.getSource()==chu){
Stringnum11=number1.getText();
num1=Double.parseDouble(num11);
Stringnum22=number2.getText();
num2=Double.parseDouble(num22);
res=num1/num2;
result.setText(df.format(res)+"");
}
}
}
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
JFramef=new簡單計算器16_4();
f.setSize(400,130);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
}
}
⑧ 怎麼用java編寫一個簡單的計算器
/*
* @(#)JCalculator.java 1.00 06/17/2015
*/
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
/**
* A simple calculator program.
*<p>I saw this program in a QQ group, and help a friend correct it.</p>
*
*@authorSingyuenYip
*@version1.00 12/29/2009
*@seeJFrame
*@seeActionListener
*/
{
/**
* Serial Version UID
*/
= -169068472193786457L;
/**
* This class help close the Window.
*@authorSingyuenYip
*
*/
{
publicvoidwindowClosing(WindowEvent we) {
System.exit(0);
}
}
inti;
// Strings for Digit & Operator buttons.
privatefinalString[]str= {"7","8","9","/","4","5","6","*","1",
"2","3","-",".","0","=","+"};
// Build buttons.
JButton[]buttons=newJButton[str.length];
// For cancel or reset.
JButtonreset=newJButton("CE");
// Build the text field to show the result.
JTextFielddisplay=newJTextField("0");
/**
* Constructor without parameters.
*/
publicJCalculator() {
super("Calculator");
// Add a panel.
JPanel panel1 =newJPanel(newGridLayout(4, 4));
// panel1.setLayout(new GridLayout(4,4));
for(i= 0;i<str.length;i++) {
buttons[i] =newJButton(str[i]);
panel1.add(buttons[i]);
}
JPanel panel2 =newJPanel(newBorderLayout());
// panel2.setLayout(new BorderLayout());
panel2.add("Center",display);
panel2.add("East",reset);
// JPanel panel3 = new Panel();
getContentPane().setLayout(newBorderLayout());
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(newWindowCloser());
// 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();
}
publicvoidactionPerformed(ActionEvent e) {
Object target = e.getSource();
String label = e.getActionCommand();
if(target ==reset)
handleReset();
elseif("0123456789.".indexOf(label) > 0)
handleNumber(label);
else
handleOperator(label);
}
// Is the first digit pressed?
booleanisFirstDigit=true;
/**
* Number handling.
*@paramkey the key of the button.
*/
publicvoidhandleNumber(String key) {
if(isFirstDigit)
display.setText(key);
elseif((key.equals(".")) && (display.getText().indexOf(".") < 0))
display.setText(display.getText() +".");
elseif(!key.equals("."))
display.setText(display.getText() + key);
isFirstDigit=false;
}
/**
* Reset the calculator.
*/
publicvoidhandleReset() {
display.setText("0");
isFirstDigit=true;
operator="=";
}
doublenumber= 0.0;
Stringoperator="=";
/**
* Handling the operation.
*@paramkey pressed operator's key.
*/
publicvoidhandleOperator(String key) {
if(operator.equals("+"))
number+= Double.valueOf(display.getText());
elseif(operator.equals("-"))
number-= Double.valueOf(display.getText());
elseif(operator.equals("*"))
number*= Double.valueOf(display.getText());
elseif(operator.equals("/"))
number/= Double.valueOf(display.getText());
elseif(operator.equals("="))
number= Double.valueOf(display.getText());
display.setText(String.valueOf(number));
operator= key;
isFirstDigit=true;
}
publicstaticvoidmain(String[] args) {
newJCalculator();
}
}
運行界面: