java实现计算器
① 用java编写一个计算器
importjava.awt.BorderLayout;
importjava.awt.Color;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.ImageIcon;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
importjavax.swing.SwingConstants;
{
/**
*
*/
=1L;
Resultresult=newResult();//定义text的面板
Number_Keynumber_key=newNumber_Key();//定义按钮面板
//当点击按钮+、-、*、/时,com=true
booleancom=false;
//当i=0时说明是我们第一次输入,字符串text不会累加
inti=0;
//存放text的内容
Stringtext="";
//存放点击按钮+、-、*、/之前的数值
doubledefbutton=0;
//+、-、*、/的代号分别为1,2,3,4
intsymbol=0;
//构造函数
Jisuanqi(){
super("WangJiao");//设定标题
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设定关闭窗体时退出程序
JPanelpane=newJPanel();//定义主面板
pane.setLayout(newBorderLayout());
setBounds(380,220,30,80);//前两个参数是在屏幕上显示的坐标,后两个是大小
//替换图标
ImageIconicon=newImageIcon("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();//初始化窗体大小为正好盛放所有按钮
}
//各个按钮触发的事件
publicvoidactionPerformed(ActionEvente){
/*
*如果是点击数字按钮那么先要判断是否在此之前点击了+、-、*、/、=,如果是那么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");
}
}elseif(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");
}
}elseif(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");
}
}elseif(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");
}
}elseif(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");
}
}elseif(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");
}
}elseif(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");
}
}elseif(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");
}
}elseif(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;否则保持原来的数值不变
*/
elseif(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");
}
}
}
}elseif(e.getSource()==number_key.ce){
result.text.setText("0");
i=0;
com=true;
//text="";
defbutton=0;
}
/*
*本程序不会让一个数值中出现2个以上的小数点.具体做法是:判断是否已经存在.存在就不添加,不存在就添加.
*/
elseif(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);
}
}
}//获得点击+之前的数值
elseif(e.getSource()==number_key.plus){
com=true;
i=0;
defbutton=Double.parseDouble(result.text.getText());
symbol=1;
}//获得点击-之前的数值
elseif(e.getSource()==number_key.sub){
com=true;
i=0;
defbutton=Double.parseDouble(result.text.getText());
symbol=2;
}//获得点击*之前的数值
elseif(e.getSource()==number_key.mul){
com=true;
i=0;
defbutton=Double.parseDouble(result.text.getText());
System.out.println(defbutton);
symbol=3;
}//获得点击/之前的数值
elseif(e.getSource()==number_key.div){
com=true;
i=0;
defbutton=Double.parseDouble(result.text.getText());
symbol=4;
}elseif(e.getSource()==number_key.equal){
switch(symbol){
case1:{//计算加法
doublead=defbutton
+Double.parseDouble(result.text.getText());
result.text.setText(ad+"");
i=0;
text="";
break;
}
case2:{//计算减法
doublead=defbutton
-Double.parseDouble(result.text.getText());
result.text.setText(String.valueOf(ad));
i=0;
text="";
break;
}
case3:{//计算乘法
doublead=defbutton
*Double.parseDouble(result.text.getText());
result.text.setText(ad+"");
i=0;
text="";
break;
}
case4:{//计算除法
doublead=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")
publicstaticvoidmain(String[]args){
Jisuanqiloveyou=newJisuanqi();
loveyou.show();
}
}
//计算器数字按钮定义面板
classNumber_KeyextendsJPanel{
/**
*
*/
=1L;
JButtonzero=newJButton("0");//数字键0
JButtonone=newJButton("1");//数字键1
JButtontwo=newJButton("2");//数字键2
JButtonthree=newJButton("3");//数字键3
JButtonfour=newJButton("4");//数字键4
JButtonfive=newJButton("5");//数字键5
JButtonsix=newJButton("6");//数字键6
JButtonseven=newJButton("7");//数字键7
JButtoneight=newJButton("8");//数字键8
JButtonnine=newJButton("9");//数字键9
JButtonplus=newJButton("+");
JButtonsub=newJButton("-");
JButtonmul=newJButton("*");
JButtondiv=newJButton("/");
JButtonequal=newJButton("=");
JButtonce=newJButton("清零");//置零键
JButtonpoint=newJButton(".");
Number_Key(){
setLayout(newGridLayout(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);
}
}
//计算器显示结果的窗体
classResultextendsJPanel{
/**
*
*/
=1L;
//text先是输入和结果
JTextFieldtext=newJTextField("0");
@SuppressWarnings("deprecation")
Result(){//讲输入的数字或得到的结果在text的右边显示
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.enable(false);//文本框不能编辑
setLayout(newBorderLayout());//设定布局管理器边框布局
add(text,BorderLayout.CENTER);//text放置在窗体的中间
}
}
直接复制保存成Jisuanqi.java可以直接运行了
② 用java编写计算器
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JCalculator extends JFrame implements ActionListener {
private static final long serialVersionUID = -L;
private class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
int i;
private final String[] str = { "7", "8", "9", "/", "4", "5", "6", "*", "1",
"2", "3", "-", ".", "0", "=", "+" };
// 建立按钮
JButton[] buttons = new JButton[str.length];
// 撤销重置
JButton reset = new JButton("CE");
// 建立文本域显示结果
JTextField display = new JTextField("0");
public JCalculator() {
super("Calculator");
// 添加一个面板
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);
// 添加操作动作的监听器.
for (i = 0; i < str.length; i++)
buttons[i].addActionListener(this);
// 为重置按钮添加监听器
reset.addActionListener(this);
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 (".".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 = "=";
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();
}
}
③ 如何用java编程做一个计算器
有一个现成的参考一下吧
import java.awt.event.ActionEvent;
public class Application extends JFrame {
protected String str = "";
protected boolean isChar = true;
protected boolean isEqual = false;
protected JTextField textField;
public Application() {
Listener listerner = new Listener(this);
getContentPane().setLayout(null);
JButton button = new JButton("7");
button.addActionListener(listerner);
button.setBounds(12, 69, 43, 27);
getContentPane().add(button);
textField = new JTextField();
textField.setText("0");
textField.setEditable(false);
textField.setHorizontalAlignment(JTextField.RIGHT);
textField.setBounds(12, 22, 377, 27);
getContentPane().add(textField);
textField.setColumns(10);
JButton button_1 = new JButton("8");
button_1.addActionListener(listerner);
button_1.setBounds(103, 69, 43, 27);
getContentPane().add(button_1);
JButton button_2 = new JButton("9");
button_2.addActionListener(listerner);
button_2.setBounds(182, 69, 43, 27);
getContentPane().add(button_2);
JButton button_3 = new JButton("4");
button_3.addActionListener(listerner);
button_3.setBounds(12, 106, 43, 27);
getContentPane().add(button_3);
JButton button_4 = new JButton("5");
button_4.addActionListener(listerner);
button_4.setBounds(103, 106, 43, 27);
getContentPane().add(button_4);
JButton button_5 = new JButton("6");
button_5.addActionListener(listerner);
button_5.setBounds(182, 106, 43, 27);
getContentPane().add(button_5);
JButton button_6 = new JButton("1");
button_6.addActionListener(listerner);
button_6.setBounds(12, 143, 43, 27);
getContentPane().add(button_6);
JButton button_7 = new JButton("2");
button_7.addActionListener(listerner);
button_7.setBounds(103, 143, 43, 27);
getContentPane().add(button_7);
JButton button_8 = new JButton("3");
button_8.addActionListener(listerner);
button_8.setBounds(182, 143, 43, 27);
getContentPane().add(button_8);
JButton button_9 = new JButton("+");
button_9.addActionListener(listerner);
button_9.setBounds(269, 72, 43, 27);
getContentPane().add(button_9);
JButton button_10 = new JButton("-");
button_10.addActionListener(listerner);
button_10.setBounds(346, 72, 43, 27);
getContentPane().add(button_10);
JButton button_11 = new JButton("*");
button_11.addActionListener(listerner);
button_11.setBounds(269, 109, 43, 27);
getContentPane().add(button_11);
JButton button_12 = new JButton("/");
button_12.addActionListener(listerner);
button_12.setBounds(346, 109, 43, 27);
getContentPane().add(button_12);
JButton button_13 = new JButton("=");
button_13.addActionListener(listerner);
button_13.setBounds(346, 143, 43, 27);
getContentPane().add(button_13);
JButton button_14 = new JButton("0");
button_14.addActionListener(listerner);
button_14.setBounds(103, 180, 43, 27);
getContentPane().add(button_14);
JButton btnReset = new JButton("reset");
btnReset.addActionListener(listerner);
btnReset.setBounds(269, 180, 118, 27);
getContentPane().add(btnReset);
JButton button_15 = new JButton(".");
button_15.addActionListener(listerner);
button_15.setBounds(269, 146, 43, 27);
getContentPane().add(button_15);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setSize(442, 260);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new Application();
}
}
class Listener implements ActionListener {
private Application app = null;
public Listener(Application app) {
this.app = app;
}
public void actionPerformed(ActionEvent e) {
String value = e.getActionCommand();
if (value.matches("[0-9.]")) {
if (app.isChar) {
app.textField.setText("");
app.isChar = false;
}
if (app.isEqual && app.str.matches("[0-9.]*")) {
app.str = "";
app.isEqual = false;
}
app.str += value;
app.textField.setText(app.textField.getText() + value);
} else if (value.matches("[\\+\\-\\*/]")) {
if (!app.str.substring(app.str.length() - 1)
.matches("[\\+\\-\\*/]")) {
app.str += value;
app.isChar = true;
}
} else if ("=".equals(value)) {
app.isEqual = true;
if (app.str.substring(app.str.length() - 1).matches("[\\+\\-]")) {
app.str += "0";
} else if (app.str.substring(app.str.length() - 1)
.matches("[\\*/]")) {
app.str += "1";
}
Interpreter bsh = new Interpreter();
String obj = null;
try {
obj = bsh.eval(app.str).toString();
} catch (Exception exception) {
System.out.println(exception.getMessage());
}
System.out.println(app.str);
app.textField.setText(obj);
app.str = obj;
app.isChar = true;
} else {
app.str = "";
app.textField.setText("0");
}
}
}
④ 用Java做一个简单的计算器
窗体
package Calc;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* 计算器程序
*
*/
public class CalcFrame extends JFrame {
JButton[] buttons = new JButton[16];// 16个按钮
StringBuffer sb = null;//
JTextField text1 = null;// 计算器结果显示框
String no1 = null;
String sign = null;// 表示+-*/符号
String[] s = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "-",
"*", "/", "=", "C" };// 面板上的字符
public CalcFrame() {
setTitle("计算器");
setResizable(false);
setBounds(200, 200, 300, 350);
setLayout(null);
sb = new StringBuffer();
text1 = new JTextField();
text1.setBounds(10, 10, 250, 30);// 设置位置
text1.setFont(new Font("Arial", Font.PLAIN, 20));// 设置字体
text1.setForeground(Color.RED);// 设置颜色
add(text1);
for (int i = 0; i < s.length; i++) {
buttons[i] = new JButton(s[i]);
buttons[i].setFont(new Font("Serif", Font.BOLD, 18));
add(buttons[i]);
}// 生成面板上的按钮.
buttons[0].setBounds(10, 50, 50, 40);
buttons[0].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(0);
text1.setText(sb.toString());
}
});
buttons[1].setBounds(70, 50, 50, 40);
buttons[1].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(1);
text1.setText(sb.toString());
}
});
buttons[2].setBounds(130, 50, 50, 40);
buttons[2].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(2);
text1.setText(sb.toString());
}
});
buttons[3].setBounds(190, 50, 50, 40);
buttons[3].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(3);
text1.setText(sb.toString());
}
});
buttons[4].setBounds(10, 100, 50, 40);
buttons[4].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(4);
text1.setText(sb.toString());
}
});
buttons[5].setBounds(70, 100, 50, 40);
buttons[5].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(5);
text1.setText(sb.toString());
}
});
buttons[6].setBounds(130, 100, 50, 40);
buttons[6].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(6);
text1.setText(sb.toString());
}
});
buttons[7].setBounds(190, 100, 50, 40);
buttons[7].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(7);
text1.setText(sb.toString());
}
});
buttons[8].setBounds(10, 150, 50, 40);
buttons[8].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(8);
text1.setText(sb.toString());
}
});
buttons[9].setBounds(70, 150, 50, 40);
buttons[9].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(9);
text1.setText(sb.toString());
}
});
buttons[10].setBounds(130, 150, 50, 40);
buttons[10].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sign = "+";
no1 = text1.getText();
sb.delete(0, sb.capacity());
}
});
buttons[11].setBounds(190, 150, 50, 40);
buttons[11].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sign = "-";
no1 = text1.getText();
sb.delete(0, sb.capacity());
}
});
buttons[12].setBounds(10, 200, 50, 40);
buttons[12].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sign = "*";
no1 = text1.getText();
sb.delete(0, sb.capacity());
}
});
buttons[13].setBounds(70, 200, 50, 40);
buttons[13].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sign = "/";
no1 = text1.getText();
sb.delete(0, sb.capacity());
}
});
buttons[14].setForeground(Color.RED);
buttons[14].setBounds(130, 200, 50, 40);
buttons[14].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int sum = 0;//最终结果
if (sign.equals("+")) {
int no2 = Integer.parseInt(no1);//取得前一个数
int no3 = Integer.parseInt(text1.getText());//取得现在的数
sum = no2 + no3;//累加
text1.setText(String.valueOf(sum));
}
if (sign.equals("-")) {
int no2 = Integer.parseInt(no1);
int no3 = Integer.parseInt(text1.getText());
sum = no2 - no3;
text1.setText(String.valueOf(sum));
}
if (sign.equals("*")) {
int no2 = Integer.parseInt(no1);
int no3 = Integer.parseInt(text1.getText());
sum = no2 * no3;
text1.setText(String.valueOf(sum));
}
if (sign.equals("/")) {
int no2 = Integer.parseInt(no1);
int no3 = Integer.parseInt(text1.getText());
sum = no2 / no3;
text1.setText(String.valueOf(sum));
}
}
});
buttons[15].setBounds(190, 200, 50, 40);
buttons[15].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.delete(0, sb.capacity());//清除sb的内容
text1.setText("");//结果框设置为空
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//响应关闭窗口
setVisible(true);//显示窗口
}
}
2.主程序类
package Calc;
public class CalcTest {
public static void main(String[] args) {
CalcFrame f = new CalcFrame();
}
}
学习Java就到IT学习联盟
⑤ 怎么用JAVA编程编写一个计算器
打开IED:打开自己java编程的软件,采用的是eclipse软件。
建立java工程。
编写类。
⑥ 用JAVA编写的计算器
package main;
import java.awt.Button;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Calculator extends JFrame implements ActionListener {
static Panel pan = new Panel();
static JTextField textField = new JTextField("0");
static Button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, bp, ba, bs, bm, bd,
be, bc, bt, bf, bh;
private StringBuffer temp = new StringBuffer("");
private String optValue = "0";
private String optType="";
private boolean isChoiseOptType=true;
public void init() {
b0 = new Button("0");
b0.addActionListener(this);
b1 = new Button("1");
b1.addActionListener(this);
b2 = new Button("2");
b2.addActionListener(this);
b3 = new Button("3");
b3.addActionListener(this);
b4 = new Button("4");
b4.addActionListener(this);
b5 = new Button("5");
b5.addActionListener(this);
b6 = new Button("6");
b6.addActionListener(this);
b7 = new Button("7");
b7.addActionListener(this);
b8 = new Button("8");
b8.addActionListener(this);
b9 = new Button("9");
b9.addActionListener(this);
bp = new Button(".");
bp.addActionListener(this);
ba = new Button("+");
ba.addActionListener(this);
bs = new Button("-");
bs.addActionListener(this);
bm = new Button("*");
bm.addActionListener(this);
bd = new Button("/");
bd.addActionListener(this);
be = new Button("=");
be.addActionListener(this);
bc = new Button("c");
bc.addActionListener(this);
bt = new Button("退格");
bt.addActionListener(this);
bf = new Button("1/x");
bf.addActionListener(this);
bh = new Button("+/-");
bh.addActionListener(this);
this.setTitle("计算机");
this.setLayout(null);
this.setSize(260, 300);
this.setResizable(false);
GridLayout grid = new GridLayout(4, 5);
pan.setLayout(grid);
pan.setBounds(20, 60, 150, 120);
textField.setBounds(20, 35, 150, 20);
textField.setBackground(Color.cyan);
textField.setHorizontalAlignment(textField.RIGHT);
textField.setEditable(false);
pan.add(b1);
pan.add(b2);
pan.add(b3);
pan.add(ba);
pan.add(bc);
pan.add(b4);
pan.add(b5);
pan.add(b6);
pan.add(bs);
pan.add(bt);
pan.add(b7);
pan.add(b8);
pan.add(b9);
pan.add(bm);
pan.add(bf);
pan.add(b0);
pan.add(bh);
pan.add(bp);
pan.add(bd);
pan.add(be);
this.add(textField);
this.add(pan);
}
public static void main(String[] args) {
Calculator frm = new Calculator();
frm.init();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}
@SuppressWarnings("static-access")
@Override
public void actionPerformed(ActionEvent e) {
String value="0";
if (e.getSource().equals(b0)) {
this.temp.append(b0.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b1)) {
this.temp.append(b1.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b2)) {
this.temp.append(b2.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b3)) {
this.temp.append(b3.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b4)) {
this.temp.append(b4.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b5)) {
this.temp.append(b5.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b6)) {
this.temp.append(b6.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b7)) {
this.temp.append(b7.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b8)) {
this.temp.append(b8.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b9)) {
this.temp.append(b9.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(bp)) {
if(this.temp.length()<=0)
this.temp.append("0");
this.temp.append(bp.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(ba)) {
if(!isChoiseOptType){
value=this.textField.getText();
if(value.lastIndexOf(".")==value.length()-1){
value=value.substring(0,value.length()-1);
}
this.optValue=value;
this.temp=new StringBuffer("");
}
this.optType=ba.getLabel();
isChoiseOptType=true;
} else if (e.getSource().equals(bs)) {
if(!isChoiseOptType){
value=this.textField.getText();
if(value.lastIndexOf(".")==value.length()-1){
value=value.substring(0,value.length()-1);
}
this.optValue=value;
this.temp=new StringBuffer("");
}
this.optType=bs.getLabel();
isChoiseOptType=true;
} else if (e.getSource().equals(bm)) {
if(!isChoiseOptType){
value=this.textField.getText();
if(value.lastIndexOf(".")==value.length()-1){
value=value.substring(0,value.length()-1);
}
this.optValue=value;
this.temp=new StringBuffer("");
}
this.optType=bm.getLabel();
isChoiseOptType=true;
} else if (e.getSource().equals(bd)) {
if(!isChoiseOptType){
value=this.textField.getText();
if(value.lastIndexOf(".")==value.length()-1){
value=value.substring(0,value.length()-1);
}
this.optValue=value;
this.temp=new StringBuffer("");
}
this.optType=bd.getLabel();
isChoiseOptType=true;
}else if (e.getSource().equals(be)) {
if(!this.optType.equals("")){
BigDecimal opt1=new BigDecimal(this.optValue);
value=this.textField.getText();
if(value.lastIndexOf(".")==value.length()-1){
value=value.substring(0,value.length()-1);
}
BigDecimal opt2=new BigDecimal(value);
BigDecimal result=new BigDecimal(0);
if(this.optType.equals("+")){
result=opt1.add(opt2);
}else if(this.optType.equals("-")){
result=opt1.subtract(opt2);
}else if(this.optType.equals("*")){
result=opt1.multiply(opt2);
}else if(this.optType.equals("/")){
result=opt1.divide(opt2);
}else if(this.optType.equals("%")){
result=opt1.remainder(opt2);
}
this.textField.setText(result.toString());
this.temp=new StringBuffer("");
isChoiseOptType=false;
this.optValue="0";
}
} else if (e.getSource().equals(bc)) {
this.temp=new StringBuffer();
this.textField.setText("0");
} else if (e.getSource().equals(bt)) {
value=this.textField.getText();
value=value.substring(0,value.length()-1);
if(value.indexOf("-")>=0 && value.length()<=1){
value="0";
this.temp=new StringBuffer("");
}else{
this.temp=new StringBuffer(value);
}
this.textField.setText(value);
}else if (e.getSource().equals(bh)) {
value=this.textField.getText();
if(value.indexOf("-")==0){
value=value.substring(1,value.length());
}else{
value="-"+value;
}
this.temp=new StringBuffer(value);
this.textField.setText(value);
} else if (e.getSource().equals(bf)) {
this.optValue=this.textField.getText();
if(value.lastIndexOf(".")==value.length()-1){
this.optValue=this.optValue.substring(0,this.optValue.length()-1);
}
Integer opt1=new Integer(this.optValue);
if(!opt1.toString().equals("0")){
this.textField.setText(1.0/opt1.intValue()+"");
System.out.println(1/opt1.intValue()+"");
}else{
this.textField.setText("0");
}
this.temp=new StringBuffer("");
this.optType="";
this.optValue="0";
}
}
}
⑦ 用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实现一个简单的计算器。
说实在的,你写的这个计算器不怎么样。特别是布局。
我给你一个很简单的吧。你自己学习一下。。
import java.awt.*;
import java.awt.event.*;
/**
*
* @author zzj
*
*/
public class Jisuanqi extends WindowAdapter {
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
TextField txt;
private Button[] b = new Button[17];
private String ss[] = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2",
"3", "*", "清空", "0", "=", "/", "关闭" };
static double a;
static String s, str;//定义变量 创建对像
public static void main(String args[]) {
(new Jisuanqi()).frame();
}
public void frame() {
Frame fm = new Frame("简单计算器");
for (int i = 0; i <= 16; i++) {
b[i] = new Button(ss[i]);
}
for (int i = 0; i <= 15; i++) {
p2.add(b[i]);
} //创建按钮 并添加到P2
b[16].setBackground(Color.yellow);
txt = new TextField(15);
txt.setEditable(false);
for (int i = 0; i <= 16; i++) {
b[i].addActionListener(new buttonlistener());//添加监听器
}
b[16].addActionListener(new close());
fm.addWindowListener(this);
fm.setBackground(Color.red);
p1.setLayout(new BorderLayout());
p1.add(txt, "North");
p2.setLayout(new GridLayout(4, 4));
p3.setLayout(new BorderLayout());
p3.add(b[16]);
fm.add(p1, "North");
fm.add(p2, "Center");
fm.add(p3, "South");
fm.pack();
fm.setVisible(true);//都是些窗中设置 添加相关组件和监听器
}
public void windowClosing(WindowEvent e) {
System.exit(0);//退出系统
}
class buttonlistener implements ActionListener {//编写监听器事件 通过按键得出给果
public void actionPerformed(ActionEvent e) {
Button btn = (Button) e.getSource();
if (btn.getLabel() == "=") {
jisuan();
str = String.valueOf(a);
txt.setText(str);
s = "";
} else if (btn.getLabel() == "+") {
jisuan();
txt.setText("");
s = "+";
} else if (btn.getLabel() == "-") {
jisuan();
txt.setText("");
s = "-";
} else if (btn.getLabel() == "/") {
jisuan();
txt.setText("");
s = "/";
} else if (btn.getLabel() == "*") {
jisuan();
txt.setText("");
s = "*";
} else {
txt.setText(txt.getText() + btn.getLabel());
if (btn.getLabel() == "清空")
txt.setText("");
}
}
public void jisuan() {//编写具体计算方法
if (s == "+")
a += Double.parseDouble(txt.getText());
else if (s == "-")
a -= Double.parseDouble(txt.getText());
else if (s == "*")
a *= Double.parseDouble(txt.getText());
else if (s == "/")
a /= Double.parseDouble(txt.getText());
else
a = Double.parseDouble(txt.getText());
}
}
}
class close implements ActionListener {//退出
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
⑨ 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("计算器"); // 设定标题
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放置在窗体的中间
}
}
⑩ 用JAVA编写一个简单的计算器,要求如下
太麻烦了 说个思路, 过去字符串后 先获取+-*%的下标.然后然后分割,获取到一个数组或list
然后循环获取() 按照数学运算顺序拼起来,
然后把公式拆分一步一步操作就得出结果啦