導航:首頁 > 編程語言 > 簡單的計算器java代碼

簡單的計算器java代碼

發布時間:2023-07-16 06:32:18

1. 怎麼用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();

}

}


運行界面:

2. 用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();
}
}

3. java編一個計算器的代碼

界面漂亮堪比系統自帶計算器,功能完美加減乘除開平方等等全部具備,還有清零按鈕,小數點的使用,連加連乘功能完全參考系統官方計算器經過長期調試改進而成,馬上拷貝代碼拿去試試看吧,絕不後悔!

代碼如下:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class Counter {

public static void main(String[] args) {

CounterFrame frame = new CounterFrame();

frame.show();
}
}

class CounterFrame extends JFrame {

public CounterFrame() {

JMenuBar menuBar = new JMenuBar();
JMenu menuFile = new JMenu();
JMenu menuFile1 = new JMenu();
JMenu menuFile2 = new JMenu();
JMenu menuFile3 = new JMenu();
JMenuItem menuFileExit = new JMenuItem();

menuFile.setText("文件");
menuFile1.setText("編輯");
menuFile2.setText("查看");
menuFile3.setText("幫助");

menuFileExit.setText("退出");

menuFileExit.addActionListener
(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
CounterFrame.this.windowClosed();
}
}
);
menuFile.add(menuFileExit);
menuBar.add(menuFile);
menuBar.add(menuFile1);
menuBar.add(menuFile2);
menuBar.add(menuFile3);

setTitle("計算器");
setJMenuBar(menuBar);
setSize(new Dimension(400, 280));

this.getContentPane().add(new Allpanel());

this.addWindowListener
(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
CounterFrame.this.windowClosed();
}
}
);
}

protected void windowClosed() {

System.exit(0);
}
}

class Tool {

public static Tool instance;
private JTextField field;
private Tool() {
this.field=new JTextField(30);
this.field.setHorizontalAlignment(JTextField.RIGHT);

}

public static Tool getinstance()
{
if(instance==null)
{
instance=new Tool();
}
return instance;

}

public JTextField getfield()
{
return (this.field);
}

}

class Allpanel extends JPanel {

public Allpanel() {
this.setLayout(new BorderLayout(0,7));
Northpanel np=new Northpanel();
Centerpanel cp=new Centerpanel();
this.add(np,BorderLayout.NORTH);
this.add(cp,BorderLayout.CENTER);
}
}

class Centercenter extends JPanel {

static Vector Vec=new Vector();
static Vector vc=new Vector();
static Vector vc1=new Vector();
static Vector vc2=new Vector();
static Vector vc3=new Vector();

static String begin="yes";
static double add;
static double jq;
static double cs;
static double cq;

static double dy;
static String jg;
static String what;
static double tool=0;
static String to="yes";

/**
* Method Centercenter
*
*
*/
public Centercenter() {
// TODO: Add your code here
final JTextField text=Tool.getinstance().getfield();
this.setLayout(new GridLayout(4,5,3,3));
String arg[] ={"7","8","9","/","sqrt","4","5","6","*","%","1","2","3","-","1/x","0","+/-",".","+","="};

for(int i=0;i<20;i++)
{
final JButton b=new JButton(arg[i]);
//this.add(new JButton(arg[i]));
this.add(b);

if(i==0||i==1||i==2||i==5||i==6||i==7||i==10||i==11||i==12||i==15)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String mark=b.getText();
String ma=text.getText();

if(vc3.contains("v3"))
{
text.setText("0."+mark);
vc3.clear();
}

else if(vc.contains("a"))
{
if(vc2.contains("v2"))
{
text.setText("0."+mark);
vc.clear();
vc2.clear();

}
else
{
text.setText(mark);
vc.clear();
Vec.clear();
Vec.add(mark);
}

}
else
{
text.setText(ma.trim()+mark);
Vec.add(mark);
}

begin="no";
to="yes";

}
});
}

if(i==17)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

{
String mar=b.getText();
String m=text.getText();
if("yes".equals(begin))
{
vc3.add("v3");
}

if(vc1.contains("v1"))
{
vc2.add("v2");
vc1.clear();
}

if(!Vec.contains(".")&&!vc.contains("a"))
{
text.setText(m.trim()+mar);
Vec.add(".");
}

}
});
}

if(i==18)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

{
String ma=text.getText();
add=Double.parseDouble(ma);
if(what==null)
{
tool=add;
what="add";
}
else
{
tool=tool+add;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="+";
}
});
}
if(i==13)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

{
String ma=text.getText();
jq=Double.parseDouble(ma);

if(what==null)
{
tool=jq;
what="jq";
}
else
{
tool=tool-jq;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="-";
}
});
}

if(i==3)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

{
String ma=text.getText();
cq=Double.parseDouble(ma);
if(what==null)
{
tool=cq;
what="cq";
}

else
{
tool=tool/cq;
text.setText(String.valueOf((tool)));
}

vc.add("a");
vc1.add("v1");
to="/";
}
});
}

if(i==4)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

{
String ma=text.getText();
cq=Double.parseDouble(ma);

text.setText(String.valueOf(Math.sqrt(cq)));
}
});
}

if(i==8)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

{
String ma=text.getText();
cs=Double.parseDouble(ma);
if(what==null)
{
tool=cs;
what="cs";
}
else
{
tool=tool*cs;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="*";
}
});
}

if(i==19)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

{
String ma=text.getText();
dy=Double.parseDouble(ma);
if(what=="add")
{
jg=String.valueOf((tool+dy));
}
if(what=="jq")
{
jg=String.valueOf((tool-dy));
}
if(what=="cs")
{
jg=String.valueOf((tool*dy));
}
if(what=="cq")
{
jg=String.valueOf((tool/dy));
}
if(what==null)
{
if(to=="+")
{
tool=add;
jg=String.valueOf(tool+dy);
}

else if(to=="-")
{
tool=jq;
jg=String.valueOf(dy-tool);
}

else if(to=="*")
{
tool=cs;
jg=String.valueOf(dy*tool);
}

else if(to=="/")
{
tool=cq;
jg=String.valueOf(dy/tool);
}

else
{
jg=String.valueOf(dy);
}
}

text.setText(jg);

Vec.clear();
Vec.add(".");
vc.add("a");
vc1.add("v1");
what=null;
tool=0;

}
});
}

}

}

}

class Centernorth extends JPanel {

public Centernorth() {

final JTextField text=Tool.getinstance().getfield();

JButton jb1=new JButton("Backspace");
JButton jb2=new JButton(" CE ");
JButton jb3=new JButton(" C ");
this.add(jb1);
this.add(jb2);
this.add(jb3);

jb1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e)
{
String back=Tool.getinstance().getfield().getText();
text.setText(backmethod(back));
Centercenter.Vec.remove(Centercenter.Vec.size()-1);

}

});

jb3.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e)
{

text.setText("0.");
Centercenter.Vec.clear();
Centercenter.Vec.add(".");
Centercenter.vc.add("a");
Centercenter.begin="yes";
Centercenter.vc1.clear();
Centercenter.what=null;
Centercenter.tool=0;

}

});

}

public String backmethod(String str)
{
return str.substring(0,str.length()-1);
}

}

class Centerpanel extends JPanel {

public Centerpanel() {
this.setLayout(new BorderLayout(8,7));
Centernorth cn=new Centernorth();
Centercenter cc=new Centercenter();
Centerwest cw=new Centerwest();
this.add(cn,BorderLayout.NORTH);
this.add(cc,BorderLayout.CENTER);
this.add(cw,BorderLayout.WEST);
}
}

class Centerwest extends JPanel {

public Centerwest() {
this.setLayout(new GridLayout(4,1,3,3));
this.add(new JButton("MC"));
this.add(new JButton("MR"));
this.add(new JButton("MS"));
this.add(new JButton("M+"));

}

}

class Northpanel extends JPanel {

private JTextField tf;

public Northpanel() {
tf=Tool.getinstance().getfield();
this.add(tf);
}
}

---------------------------------------------------------------------------
=============《按你要求特意後改過的最簡單功能的代碼如下》========================

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class Counter2 {

public static void main(String[] args) {

CounterFrame frame = new CounterFrame();

frame.show();
}
}

class CounterFrame extends JFrame {

public CounterFrame() {

setTitle("計算器");
setSize(new Dimension(400, 280));

this.getContentPane().add(new Allpanel());

this.addWindowListener
(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
CounterFrame.this.windowClosed();
}
}
);
}

protected void windowClosed() {

System.exit(0);
}
}

class Tool {

public static Tool instance;
private JTextField field;
private Tool() {
this.field=new JTextField(30);
this.field.setHorizontalAlignment(JTextField.RIGHT);

}

public static Tool getinstance()
{
if(instance==null)
{
instance=new Tool();
}
return instance;

}

public JTextField getfield()
{
return (this.field);
}

}

class Allpanel extends JPanel {

public Allpanel() {
this.setLayout(new BorderLayout(0,7));
Northpanel np=new Northpanel();
Centerpanel cp=new Centerpanel();
this.add(np,BorderLayout.NORTH);
this.add(cp,BorderLayout.CENTER);
}
}

class Centercenter extends JPanel {

static Vector Vec=new Vector();
static Vector vc=new Vector();
static Vector vc1=new Vector();
static Vector vc2=new Vector();
static Vector vc3=new Vector();

static String begin="yes";
static double add;
static double jq;
static double cs;
static double cq;

static double dy;
static String jg;
static String what;
static double tool=0;
static String to="yes";

/**
* Method Centercenter
*
*
*/
public Centercenter() {
// TODO: Add your code here
final JTextField text=Tool.getinstance().getfield();
this.setLayout(new GridLayout(4,5,3,3));
String arg[] ={"7","8","9","/","4","5","6","*","1","2","3","-","0","=",".","+"};

for(int i=0;i<16;i++)
{
final JButton b=new JButton(arg[i]);
//this.add(new JButton(arg[i]));
this.add(b);

if(i==0||i==1||i==2||i==4||i==5||i==6||i==8||i==9||i==10||i==12)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String mark=b.getText();
String ma=text.getText();

if(vc3.contains("v3"))
{
text.setText("0."+mark);
vc3.clear();
}

else if(vc.contains("a"))
{
if(vc2.contains("v2"))
{
text.setText("0."+mark);
vc.clear();
vc2.clear();

}
else
{
text.setText(mark);
vc.clear();
Vec.clear();
Vec.add(mark);
}

}
else
{
text.setText(ma.trim()+mark);
Vec.add(mark);
}

begin="no";
to="yes";

}
});
}

if(i==14)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

{
String mar=b.getText();
String m=text.getText();
if("yes".equals(begin))
{
vc3.add("v3");
}

if(vc1.contains("v1"))
{
vc2.add("v2");
vc1.clear();
}

if(!Vec.contains(".")&&!vc.contains("a"))
{
text.setText(m.trim()+mar);
Vec.add(".");
}

}
});
}

if(i==15)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

{
String ma=text.getText();
add=Double.parseDouble(ma);
if(what==null)
{
tool=add;
what="add";
}
else
{
tool=tool+add;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="+";
}
});
}
if(i==11)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

{
String ma=text.getText();
jq=Double.parseDouble(ma);

if(what==null)
{
tool=jq;
what="jq";
}
else
{
tool=tool-jq;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="-";
}
});
}

if(i==3)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

{
String ma=text.getText();
cq=Double.parseDouble(ma);
if(what==null)
{
tool=cq;
what="cq";
}

else
{
tool=tool/cq;
text.setText(String.valueOf((tool)));
}

vc.add("a");
vc1.add("v1");
to="/";
}
});
}

if(i==7)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

{
String ma=text.getText();
cs=Double.parseDouble(ma);
if(what==null)
{
tool=cs;
what="cs";
}
else
{
tool=tool*cs;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="*";
}
});
}

if(i==13)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

{
String ma=text.getText();
dy=Double.parseDouble(ma);
if(what=="add")
{
jg=String.valueOf((tool+dy));
}
if(what=="jq")
{
jg=String.valueOf((tool-dy));
}
if(what=="cs")
{
jg=String.valueOf((tool*dy));
}
if(what=="cq")
{
jg=String.valueOf((tool/dy));
}
if(what==null)
{
if(to=="+")
{
tool=add;
jg=String.valueOf(tool+dy);
}

else if(to=="-")
{
tool=jq;
jg=String.valueOf(dy-tool);
}

else if(to=="*")
{
tool=cs;
jg=String.valueOf(dy*tool);
}

else if(to=="/")
{
tool=cq;
jg=String.valueOf(dy/tool);
}

else
{
jg=String.valueOf(dy);
}
}

text.setText(jg);

Vec.clear();
Vec.add(".");
vc.add("a");
vc1.add("v1");
what=null;
tool=0;

}
});
}

}

}

}

class Centernorth extends JPanel {

public Centernorth() {

final JTextField text=Tool.getinstance().getfield();

}

}

class Centerpanel extends JPanel {

public Centerpanel() {
this.setLayout(new BorderLayout(8,7));
Centernorth cn=new Centernorth();
Centercenter cc=new Centercenter();
Centerwest cw=new Centerwest();
this.add(cn,BorderLayout.NORTH);
this.add(cc,BorderLayout.CENTER);
this.add(cw,BorderLayout.WEST);
}
}

class Centerwest extends JPanel {

public Centerwest() {

}

}

class Northpanel extends JPanel {

private JTextField tf;

public Northpanel() {
tf=Tool.getinstance().getfield();
this.add(tf);
}
}

------------------------------------------------------------

才子_輝祝您愉快!

4. 編寫java程序簡單計算器

主要涉及的知識點: 類的寫法, 以及方法的調用 .建議多做練習. 如果有看不懂的地方. 可以繼續追問,一起討論.

參考代碼如下

//Number類
classNumber{

privateintn1;//私有的整型數據成員n1
privateintn2;//私有的整型數據成員n2

//通過構造函數給n1和n2賦值
publicNumber(intn1,intn2){
this.n1=n1;
this.n2=n2;
}

//加法
publicintaddition(){
returnn1+n2;
}

//減法
publicintsubtration(){
returnn1-n2;
}

//乘法
publicintmultiplication(){
returnn1*n2;
}

//除法(可能除不盡,所以使用double作為返回類型)
publicdoubledivision(){
returnn1*1.0/n2;//通過n1*1.0把計算結果轉換成double類型.
}
}

//Exam4類
publicclassExam4{
publicstaticvoidmain(String[]args){
Numbernumber=newNumber(15,6);//創建Number類的對象
//下面的是調用方法得到返回值進行輸出顯示
System.out.println("加法"+number.addition());
System.out.println("減法"+number.subtration());
System.out.println("乘法"+number.multiplication());
System.out.println("除法"+number.division());

}
}

5. 求一個用JAVA編寫的計算器程序(1)實現簡單加、減、乘、除的運算。 (

public
MyCalculator()
{
f
=
new
JFrame("計算器ByMdou");
Container
contentPane
=
f.getContentPane();
/****************菜單的創建開始**************************************/
JMenuBar
mBar
=
new
JMenuBar();
mBar.setOpaque(true);
mEdit
=
new
JMenu("編輯(E)");
mEdit.setMnemonic(KeyEvent.VK_E);
mCopy
=
new
JMenuItem("復制(C)");
mEdit.add(mCopy);
mPaste
=
new
JMenuItem("粘貼(P)");
mEdit.add(mPaste);
mView
=
new
JMenu("查看(V)");
mView.setMnemonic(KeyEvent.VK_V);
mView.add(new
JMenuItem("標准型"));
mView.add(new
JMenuItem("科學型"));
mView.addSeparator();
mView.add(new
JMenuItem("查看分組"));
mHelp
=
new
JMenu("幫助(H)");
mHelp.setMnemonic(KeyEvent.VK_H);
mHelp.add(new
JMenuItem("幫助主題"));
mHelp.addSeparator();
mHelp.add(new
JMenuItem("關於計算器"));
mBar.add(mEdit);
mBar.add(mView);
mBar.add(mHelp);
f.setJMenuBar(mBar);
contentPane.setLayout(new
BorderLayout
());
JPanel
pTop
=
new
JPanel();
tResult
=
new
JTextField("0.",26);
tResult.setHorizontalAlignment(JTextField.RIGHT
);
tResult.setEditable(false);
pTop.add(tResult);
contentPane.add(pTop,BorderLayout.NORTH);
JPanel
pBottom
=
new
JPanel();
pBottom.setLayout(new
BorderLayout());
JPanel
pLeft
=
new
JPanel();
pLeft.setLayout(new
GridLayout(5,1,3,3));
bM
=
new
JButton("
");
bM.setEnabled(false);
pLeft.add(bM);
bOther
=
new
JButton("MC");
bOther.addActionListener(this);
bOther.setForeground(Color.RED);
bOther.setMargin(new
Insets(3,2,3,2));
pLeft.add(bOther);
bOther
=
new
JButton("MR");
bOther.addActionListener(this);
bOther.setForeground(Color.RED);
bOther.setMargin(new
Insets(3,2,3,2));
pLeft.add(bOther);
bOther
=
new
JButton("MS");
bOther.addActionListener(this);
bOther.setForeground(Color.RED);
bOther.setMargin(new
Insets(3,2,3,2));
pLeft.add(bOther);
bOther
=
new
JButton("M+");
bOther.addActionListener(this);
bOther.setForeground(Color.RED);
bOther.setMargin(new
Insets(3,2,3,2));
pLeft.add(bOther);

6. 求簡單java寫計算器代碼加減乘除

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Calculator extends JFrame implements ActionListener
{
private boolean dotExist, operated, equaled; // 幫助運算的布爾變數
private double storedNumber; // 目前的結果
private char lastOperator; // 表示上一運算符
private JTextField operation; // 結果欄
private JButton dot, plus, minus, multi, div, sqrt, equal, changePN, clear; // 運算符
private JButton[] numbers; // 數字

// 構造者
public Calculator()
{
setTitle("Calculator");
// 初始化變數
dotExist = false; // 表示當前的數是否有小數點
operated = false; // 表示任意運算符是否被按下
equaled = false; // 表示等號是否被按下
storedNumber = 0;
lastOperator = '?';
// 初始化窗口變數
operation = new JTextField("0");
operation.setEditable(false);
numbers = new JButton[10];
for (int i = 0; i < 10; i++)
numbers[i] = new JButton("" + i);
dot = new JButton(".");
plus = new JButton("+");
minus = new JButton("-");
multi = new JButton("*");
div = new JButton("/");
sqrt = new JButton("√");
equal = new JButton("=");
changePN = new JButton("±");
clear = new JButton("AC");
// 將窗口物體放入窗口
GridBagLayout layout = new GridBagLayout();
getContentPane().setLayout(layout);
addComponent(layout, operation, 0, 0, 4, 1);
addComponent(layout, numbers[1], 1, 0, 1, 1);
addComponent(layout, numbers[2], 1, 1, 1, 1);
addComponent(layout, numbers[3], 1, 2, 1, 1);
addComponent(layout, numbers[4], 2, 0, 1, 1);
addComponent(layout, numbers[5], 2, 1, 1, 1);
addComponent(layout, numbers[6], 2, 2, 1, 1);
addComponent(layout, numbers[7], 3, 0, 1, 1);
addComponent(layout, numbers[8], 3, 1, 1, 1);
addComponent(layout, numbers[9], 3, 2, 1, 1);
addComponent(layout, dot, 4, 0, 1, 1);
addComponent(layout, numbers[0], 4, 1, 1, 1);
addComponent(layout, sqrt, 4, 2, 1, 1);
addComponent(layout, plus, 1, 3, 1, 1);
addComponent(layout, minus, 2, 3, 1, 1);
addComponent(layout, multi, 3, 3, 1, 1);
addComponent(layout, div, 4, 3, 1, 1);
addComponent(layout, equal, 5, 0, 2, 1);
addComponent(layout, changePN, 5, 2, 1, 1);
addComponent(layout, clear, 5, 3, 1, 1);
}

// 對按鈕進行反應的方法
public void actionPerformed(ActionEvent e)
{
JButton btn = (JButton)e.getSource();
if (btn == clear)
{
operation.setText("0");
dotExist = false;
storedNumber = 0;
lastOperator = '?';
}
else if (btn == equal)
{
operate('=');
equaled = true;
}
else if (btn == plus)
{
operate('+');
equaled = false;
}
else if (btn == minus)
{
operate('-');
equaled = false;
}
else if (btn == multi)
{
operate('*');
equaled = false;
}
else if (btn == div)
{
operate('/');
equaled = false;
}
else if (btn == changePN)
{
operate('p');
operate('=');
equaled = true;
}
else if (btn == sqrt)
{
operate('s');
operate('=');
equaled = true;
}
else
{
if (equaled)
storedNumber = 0;
for (int i = 0; i < 10; i++)
if (btn == numbers[i])
{
if (operation.getText().equals("0"))
operation.setText("" + i);
else if(! operated)
operation.setText(operation.getText() + i);
else
{
operation.setText("" + i);
operated = false;
}
}
if (btn == dot && ! dotExist)
{
operation.setText(operation.getText() + ".");
dotExist = true;
}
}
}
// 進行運算的方法
private void operate(char operator)
{
double currentNumber = Double.valueOf(operation.getText()).doubleValue();
if (lastOperator == '?')
storedNumber = currentNumber;
else if (lastOperator == '+')
storedNumber += currentNumber;
else if (lastOperator == '-')
storedNumber -= currentNumber;
else if (lastOperator == '*')
storedNumber *= currentNumber;
else if (lastOperator == '/')
storedNumber /= currentNumber;
else if (lastOperator == 'p')
storedNumber *= -1;
else if (lastOperator == 's')
storedNumber = Math.sqrt(currentNumber);
else if (lastOperator == '=' && equaled)
storedNumber = currentNumber;
operation.setText("" + storedNumber);
operated = true;
lastOperator = operator;
}

// 快捷使用GridBagLayout的方法
private void addComponent(GridBagLayout layout, Component component, int row, int col, int width, int height)
{
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(10, 2, 10, 2);
constraints.weightx = 100;
constraints.weighty = 100;
constraints.gridx = col;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
if (component instanceof JButton)
((JButton)component).addActionListener(this);
getContentPane().add(component);
}

// 主方法初始化並顯示窗口
public static void main(String[] args)
{
Calculator calc = new Calculator();
calc.setSize(290, 400);
calc.setVisible(true);
}
}

閱讀全文

與簡單的計算器java代碼相關的資料

熱點內容
編譯器怎麼通過系統控制台輸出的 瀏覽:467
拆傢具用什麼app 瀏覽:45
單片機國內外 瀏覽:651
函數的運演算法則題目 瀏覽:719
有免費編譯軟體嗎 瀏覽:918
java互聯網公司 瀏覽:70
對弈下象棋的app哪裡好 瀏覽:707
有什麼食譜app推薦 瀏覽:471
python實現動態口令 瀏覽:825
我的世界電腦伺服器地址怎麼添加 瀏覽:850
傳奇地圖怎麼加密到pak 瀏覽:977
linux刪除mysql用戶 瀏覽:755
圖案設計pdf 瀏覽:586
pdf編輯器在線 瀏覽:471
華為雲雲耀伺服器如何關機 瀏覽:994
數字加密的歷史 瀏覽:614
宏傑文件夾打不開 瀏覽:819
施工日記app哪個好 瀏覽:566
什麼是壓縮機的排氣量 瀏覽:538
在哪個app可以預約一科考試 瀏覽:635