成都网站建设设计

将想法与焦点和您一起共享

添加计算器代码java,计算器编写代码

JAVA简单咋做,计算器代码

简单写了下,代码如下请参照:

10年积累的网站建设、成都网站建设经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站设计后付款的网站建设流程,更有孝南免费网站建设让你可以放心的选择与我们合作。

/**

* 计算器类

* @author Administrator

*

*/

public class Calculator extends JFrame implements ActionListener {

private static final long serialVersionUID = 3868243398506940702L;

// 文本框

private JTextField result;

// 按钮数组

private JButton[] buttons;

// 按钮文本

private final String[] characters = { "7", "8", "9", "/", "4", "5", "6",

"*", "1", "2", "3", "-", "0", ".", "=", "+" };

// 是否为第一个输入的数字

private boolean isFirstDigit = true;

// 运算结果

private double resultNum = 0.0;

// 运算符

private String operator = "=";

public Calculator(String title) {

// 设置标题栏

super(title);

// 初始化各组件

init();

// 注册各组件监听器

registerListener();

// 显示窗体

setVisible(true);

}

/**

* 初始化各组件

*/

private void init() {

// 常用属性初始化

setSize(220, 200);

setResizable(false);

setLocationRelativeTo(null);

setDefaultCloseOperation(EXIT_ON_CLOSE);

/* 文本框对象初始化 */

result = new JTextField("0");

// 文本右对齐

result.setHorizontalAlignment(JTextField.RIGHT);

// 设置是否可编辑

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);

}

/**

* 注册监听器

*/

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)) { // 数字或小数点

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)) { // 处理数字和小数点

handleNumber(text);

} else { // 处理运算符

handleOperator(text);

}

}

/**

* 处理数字和小数点

* @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;

}

// 将文本框的值修改为运算结果

this.result.setText(String.valueOf(resultNum));

// 将点击的运算符放入operator保存

operator = text;

// 下一个数字第一次点击

isFirstDigit = true;

}

public static void main(String[] args) {

 new Calculator("My Calculator");

 }

}

运行结果如下:

JAVA 编写计算器 要代码最简单的

学java的时候自己编的,很简单,能够连续输入计算式后进行计算

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.FlowLayout;

import java.awt.Font;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.text.NumberFormat;

import java.util.ArrayList;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTextField;

/**简易计算器,能够进行简单的计算

*

* @see 2008.12.9

*/

public class CalculatorA

implements ActionListener{

private JFrame frame;

private JTextField field;

private JButton[] allButtons;

private JButton clearButton;

// private JButton backButton;

String result="";//保存结果

StringBuilder sb = new StringBuilder();//保存要进行的计算式

int x = 0; //用来判断上一次的事件类型

String str = "123+456-789*0.=/";

ArrayListString arrayList = new ArrayListString();//保存计算式,通过方法进行运算

public CalculatorA(){

frame = new JFrame("我的计算器v1.1");

frame.setLocation(300,300);

field = new JTextField(25);

allButtons = new JButton[16];

for(int i=0;iallButtons.length;i++){

allButtons[i]= new JButton(str.substring(i,i+1));

}

clearButton = new JButton("CLEAR");

// backButton = new JButton("——");

init();

setFondAndColor();

addEventHander();

}

public void init(){

frame.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(field);

for(int i=0;iallButtons.length;i++){

centerPanel.add(allButtons[i]);

}

southPanel.add(clearButton);

//southPanel.add(backButton);

frame.add(northPanel,BorderLayout.NORTH);

frame.add(centerPanel,BorderLayout.CENTER);

frame.add(southPanel,BorderLayout.SOUTH);

}

//设置输入字体

public void setFondAndColor(){

field.setFont(new Font("宋体",Font.BOLD,24));

field.setBackground(new Color(100,200,200));

field.setForeground(Color.RED);

//设置字体从右起始

field.setHorizontalAlignment(JTextField.RIGHT);

}

public void showMi(){

frame.pack();

frame.setResizable(false);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void addEventHander(){

for(int i=0;iallButtons.length;i++){

allButtons[i].addActionListener(this);

}

clearButton.addActionListener(this);

// backButton.addActionListener(this);

}

@Override

public void actionPerformed(ActionEvent e) {

String str = e.getActionCommand();//取得当前事件返回的值

if("0123456789.".indexOf(str)!=-1){

if(x == 0){ //当x为0时表示还没有进行输入

result=str;

sb.append(str);

field.setText(str);

x = 1;

}

else if(x == 1){

result = result +str;

sb.append(str);

field.setText(result);

x = 1;

}

else if(x == 2){

sb.delete(0,sb.length());

result = result+str;

sb.append(str);

field.setText(result);

x = 1;

}

else if(x == 3){

result = str;

sb.delete(0,sb.length());

arrayList.clear();

field.setText(str);

sb.append(str);

field.setText(str);

x = 1;

}

else if(x == 4){

result ="";

sb.delete(0,sb.length());

arrayList.clear();

result = str;

sb.append(str);

field.setText(str);

x = 1;

}

else{

result = result +str;

sb.append(str);

field.setText(result);

x = 1;

}

}

else if("+*-/".indexOf(str)!=-1){

if(x == 0){

field.setText("");

x = 2;

}

else if(x == 1){

result = result + str;

arrayList.add(sb.toString());

arrayList.add(str);

sb.append(str);

field.setText(result);

x = 2;

}

else if(x == 2){

x = 2;

}

else if(x == 3){

field.setText(result+str);

arrayList.add(result);

arrayList.add(str);

result = result+str;

x = 2;

}

else if(x == 4){

result ="";

sb.delete(0,sb.length());

arrayList.clear();

x = 2;

}

else{

field.setText(result+str);

arrayList.add(result);

arrayList.add(str);

result = result+str;

x = 2;

}

}

else if("=".equals(str)){

if(x == 0){

field.setText("0");

arrayList.clear();

result = "0";

x = 3;

}

else if(x == 1){

try{

arrayList.add(sb.toString());

arrayList = getResult(arrayList);

result = arrayList.get(0);

field.setText(result);

arrayList.clear();

x = 3;

}catch(Exception e1){

field.setText("数据格式异常");

x = 0;

}

}

else if(x == 2){

field.setText("数据格式错误.....");

arrayList.clear();

x = 0;

}

else if(x == 3){

field.setText(result);

x = 3;

}

else if(x == 4){

result ="";

sb.delete(0,sb.length());

arrayList.clear();

x = 3;

}

else {

try{

arrayList.add(sb.toString());

arrayList = getResult(arrayList);

result = arrayList.get(0);

field.setText(result);

arrayList.clear();

x = 3;

}catch(Exception e1){

field.setText("数据格式异常");

x = 0;

}

}

}

else if("CLEAR".equals(str)){

arrayList.clear();

field.setText("0");

arrayList.add("0");

x = 4;

}

else{

if(result.length()1){

result = result.substring(0,result.length()-1);

if(sb.length()0){

sb.delete(sb.length()-1,sb.length());

}

else {

sb.delete(0,1);

}

field.setText(result);

x = 5;

}

else{

result = "";

sb.delete(0,sb.length());

arrayList.clear();

field.setText("0");

x = 0;

}

}

}

public static ArrayListString getResult(ArrayListString list){

String res = null;

String[] s = {"/","*","-","+"};

int i=0;

if(list.size()1){

for(;is.length;){

if(s[i].equals("/")){

for(int j=0;jlist.size();j++){

if(list.get(j).equals(s[i])){

res = Double.toString(Double.parseDouble(list.get(j-1))/Double.parseDouble(list.get(j+1)));

//本地的数据格式

NumberFormat nf = NumberFormat.getInstance();

res = nf.format(Double.parseDouble(res));

res = getChange(res);

list.set(j-1,res);

list.remove(j);

list.remove(j);

getResult(list);

}

}

i++;

}

else if(s[i].equals("*")){

for(int j=0;jlist.size();j++){

if(list.get(j).equals(s[i])){

res = Double.toString(Double.parseDouble(list.get(j-1))*Double.parseDouble(list.get(j+1)));

NumberFormat nf = NumberFormat.getInstance();

res = nf.format(Double.parseDouble(res));

res = getChange(res);

list.set(j-1,res);

list.remove(j);

list.remove(j);

getResult(list);

}

}

i++;

}

else if(s[i].equals("-")){

for(int j=0;jlist.size();j++){

if(list.get(j).equals(s[i])){

res = Double.toString(Double.parseDouble(list.get(j-1))-Double.parseDouble(list.get(j+1)));

NumberFormat nf = NumberFormat.getNumberInstance();

res = nf.format(Double.parseDouble(res));

res = getChange(res);

list.set(j-1,res);

list.remove(j);

list.remove(j);

getResult(list);

}

}

i++;

}

else {

for(int j=0;jlist.size();j++){

if(list.get(j).equals(s[i])){

res = Double.toString(Double.parseDouble(list.get(j-1))+Double.parseDouble(list.get(j+1)));

NumberFormat nf = NumberFormat.getInstance();

res = nf.format(Double.parseDouble(res));

res = getChange(res);

list.set(j-1,res);

list.remove(j);

list.remove(j);

getResult(list);

}

}

i++;

}

}

}

return list;

}

//对数字字符串进行排除不必要符号

public static String getChange(String res){

String s_temp = "";

char[] c = new char[res.length()];

for(int k=0;kc.length;k++){

c[k] = res.charAt(k);

}

for(int k=0;kc.length;k++){

if((c[k]= '0' c[k]= '9')|| c[k] == '.'){

s_temp += c[k];

}

}

return s_temp;

}

public static void main(String[] args){

new CalculatorA().showMi();

}

}

求用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 实现事件监听 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() { //构造属性 JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); JPanel p3 = new JPanel(); TitledBorder tb = new TitledBorder("输出"); tb.setTitleColor(Color.BLUE); //标题边框底端线 设置颜色 btnAbout = new JButton(" 关于 "); btnCancel = new JButton("Cancel"); //两个按钮 btnCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { System.exit(0); } }); //给Cancel添加事件监听 当鼠标点击时 程序结束 btnAbout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { JOptionPane.showMessageDialog(null, "黄盖!!", "消息", JOptionPane.INFORMATION_MESSAGE); } //给“关于”添加事件监听 当鼠标点击时 弹出对话框 显示黄盖 }); 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); //设置不能修改 reasult.setHorizontalAlignment(JTextField.RIGHT); // 设置文本的水平对齐方式。 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); //事件监听 + 颜色 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)); //面板上设置对齐方式 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) { // 如果数字输入结束,则将文本框置零,重新输入 reasult.setText("0"); end = false; } if ((reasult.getText()).equals("0")) { // 如果文本框的内容为零,则覆盖文本框的内容 reasult.setText(s); } else { // 如果文本框的内容不为零,则在内容后面添加数字 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; } //设计计算的过程 public static void main(String[] args) { Jisuanqi j = new Jisuanqi(); j.setTitle("+/-简易计算器"); j.setLocation(500, 280); j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //默认关闭可以关闭程序 j.setResizable(false); j.pack(); j.setVisible(true); } } 这个计算机,绝对让你满意

java加法计算器代码

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener

public class NewJFrame extends javax.swing.JFrame {

public NewJFrame() {

initComponents();

}

private void initComponents() {

jPanel1 = new javax.swing.JPanel();

jLabel1 = new javax.swing.JLabel();

jLabel2 = new javax.swing.JLabel();

jLabel3 = new javax.swing.JLabel();

num1 = new javax.swing.JTextField();

num2 = new javax.swing.JTextField();

result = new javax.swing.JTextField();

addBtn = new javax.swing.JButton();

jMenuBar1 = new javax.swing.JMenuBar();

jMenu1 = new javax.swing.JMenu();

jMenu3 = new javax.swing.JMenu();

jMenu2 = new javax.swing.JMenu();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setText("Num1:");

jLabel2.setText("Num2:");

jLabel3.setText("Num3:");

addBtn.setText("Add");

addBtn.addActionListener(new jisuanAC());

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);

jPanel1.setLayout(jPanel1Layout);

jPanel1Layout.setHorizontalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addGap(53, 53, 53)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(addBtn)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()

.addComponent(jLabel1)

.addGap(31, 31, 31)

.addComponent(num1, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))

.addGroup(jPanel1Layout.createSequentialGroup()

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jLabel2)

.addComponent(jLabel3))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)

.addComponent(result)

.addComponent(num2, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))

.addGap(168, 168, 168))

);

jPanel1Layout.setVerticalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addGap(19, 19, 19)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel1)

.addComponent(num1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel2)

.addComponent(num2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel3)

.addComponent(result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(61, 61, 61)

.addComponent(addBtn)

.addContainerGap(81, Short.MAX_VALUE))

);

jMenu1.setText("Operation");

jMenu3.setText("Add");

jMenu1.add(jMenu3);

jMenuBar1.add(jMenu1);

jMenu2.setText("Exit");

jMenuBar1.add(jMenu2);

setJMenuBar(jMenuBar1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

.addContainerGap())

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

.addContainerGap())

);

pack();

}// /editor-fold

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new NewJFrame().setVisible(true);

}

});

}

private class jisuanAC implements ActionListener

{

public void actionPerformed(ActionEvent e) {

if(e.getSource()== addBtn)

{

int number1 = Integer.parseInt(num1.getText());

int number2 = Integer.parseInt(num2.getText());

int rs = number1 + number2;

result.setText(String.valueOf(rs));

}

}

}

// Variables declaration - do not modify

private javax.swing.JButton addBtn;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JMenu jMenu1;

private javax.swing.JMenu jMenu2;

private javax.swing.JMenu jMenu3;

private javax.swing.JMenuBar jMenuBar1;

private javax.swing.JPanel jPanel1;

private javax.swing.JTextField num1;

private javax.swing.JTextField num2;

private javax.swing.JTextField result;

}

这是只有一个加法的例子!希望帮到你

用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.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的内容

String text = "";

// 存放点击按钮+、-、*、/之前的数值

double defbutton = 0;

// +、-、*、/的代号分别为1,2,3,4

int symbol = 0;

// 构造函数

Jisuanqi() {

super("WangJiao"); // 设定标题

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设定关闭窗体时退出程序

JPanel pane = new JPanel(); // 定义主面板

pane.setLayout(new BorderLayout());

setBounds(380, 220, 30, 80); // 前两个参数是在屏幕上显示的坐标,后两个是大小

// 替换图标

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按钮添加监听事件

number_key.two.addActionListener(this); // 对2按钮添加监听事件

number_key.three.addActionListener(this); // 对3按钮添加监听事件

number_key.four.addActionListener(this); // 对4按钮添加监听事件

number_key.five.addActionListener(this); // 对5按钮添加监听事件

number_key.six.addActionListener(this); // 对6按钮添加监听事件

number_key.seven.addActionListener(this); // 对7按钮添加监听事件

number_key.eight.addActionListener(this); // 对8按钮添加监听事件

number_key.nine.addActionListener(this); // 对9按钮添加监听事件

number_key.zero.addActionListener(this); // 对0按钮添加监听事件

number_key.ce.addActionListener(this); // 对置零按钮添加监听事件

number_key.plus.addActionListener(this); // 对+按钮添加监听事件

number_key.equal.addActionListener(this); // 对=按钮添加监听事件

number_key.sub.addActionListener(this); // 对-按钮添加监听事件

number_key.mul.addActionListener(this); // 对*按钮添加监听事件

number_key.div.addActionListener(this); // 对/按钮添加监听事件

number_key.point.addActionListener(this); // 对.按钮添加监听事件

setContentPane(pane);

pack(); // 初始化窗体大小为正好盛放所有按钮

}

// 各个按钮触发的事件

public void actionPerformed(ActionEvent e) {

/*

 * 如果是点击数字按钮那么先要判断是否在此之前点击了+、-、*、/、=,如果是那么com=true 如果没有com=

 * false;或者是否点击数字键,如果是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这个按钮有一定的说法,在我的程序里不会出现如00000这样的情况,我加了判断条件就是

 * 如果text中的数值=0就要判断在这个数值中是否有.存在?如果有那么就在原来数值基础之上添 加0;否则保持原来的数值不变

 */

else if (e.getSource() == number_key.zero) { // result.text.getText()是得到text里内容的意思

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)就是类型转换了,下面都是一样

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;

}

/*

 * 本程序不会让一个数值中出现2个以上的小数点.具体做法是:判断是否已经存在.存在就不添加, 不存在就添加.

 */

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);

}

}

} // 获得点击+之前的数值

else if (e.getSource() == number_key.plus) {

com = true;

i = 0;

defbutton = Double.parseDouble(result.text.getText());

symbol = 1;

} // 获得点击-之前的数值

else if (e.getSource() == number_key.sub) {

com = true;

i = 0;

defbutton = Double.parseDouble(result.text.getText());

symbol = 2;

} // 获得点击*之前的数值

else if (e.getSource() == number_key.mul) {

com = true;

i = 0;

defbutton = Double.parseDouble(result.text.getText());

System.out.println(defbutton);

symbol = 3;

} // 获得点击/之前的数值

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();

}

}

// 计算器数字按钮定义面板

class Number_Key extends JPanel {

/**

 *

 */

private static final long serialVersionUID = 1L;

JButton zero = new JButton("0"); // 数字键0

JButton one = new JButton("1"); // 数字键1

JButton two = new JButton("2"); // 数字键2

JButton three = new JButton("3"); // 数字键3

JButton four = new JButton("4"); // 数字键4

JButton five = new JButton("5"); // 数字键5

JButton six = new JButton("6"); // 数字键6

JButton seven = new JButton("7"); // 数字键7

JButton eight = new JButton("8"); // 数字键8

JButton nine = new JButton("9"); // 数字键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)); // 定义布局管理器为网格布局

setBackground(Color.blue); // 设置背景颜色

// 添加按钮

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);

}

}

// 计算器显示结果的窗体

class Result extends JPanel {

/**

 *

 */

private static final long serialVersionUID = 1L;

// text先是输入和结果

JTextField text = new JTextField("0");

@SuppressWarnings("deprecation")

Result() { // 讲输入的数字或得到的结果在text的右边显示

text.setHorizontalAlignment(SwingConstants.RIGHT);

text.enable(false); // 文本框不能编辑

setLayout(new BorderLayout()); // 设定布局管理器边框布局

add(text, BorderLayout.CENTER); // text放置在窗体的中间

}

}

直接复制 保存成Jisuanqi .java可以直接运行了


网页标题:添加计算器代码java,计算器编写代码
新闻来源:http://chengdu.cdxwcx.cn/article/hcgoch.html