用JAVA写一个计算器 要求有图形界面。简单的加减乘除,不要小数点运算。

2024-11-03 02:02:05
推荐回答(4个)
回答1:

package com;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener{
private static final long serialVersionUID = 8199443193151152362L;
private JButton bto_s=new JButton("sqrt"),bto_zf=new JButton("+/-"),bto_ce=new JButton("CE"),bto_c=new JButton("C"),bto_7=new JButton("7"),
bto_8=new JButton("8"),bto_9=new JButton("9"),bto_chu=new JButton("/"),bto_4=new JButton("4"),bto_5=new JButton("5"),
bto_6=new JButton("6"),bto_cheng=new JButton("*"),bto_1=new JButton("1"),bto_2=new JButton("2"),bto_3=new JButton("3"),
bto_jian=new JButton("-"),bto_0=new JButton("0"),bto_dian=new JButton("."),bto_deng=new JButton("="),bto_jia=new JButton("+");
JButton button[]={bto_s,bto_zf,bto_ce,bto_c,bto_7,bto_8,bto_9,bto_chu,bto_4,bto_5,bto_6,bto_cheng,bto_1,bto_2,bto_3,bto_jian,
bto_0,bto_dian,bto_deng,bto_jia};
private JTextField text_double;// = new JTextField("0");
private String operator = "="; //当前运算的运算符
private boolean firstDigit = true; // 标志用户按的是否是整个表达式的第一个数字,或者是运算符后的第一个数字
private double resultNum = 0.0; // 计算的中间结果
private boolean operateValidFlag = true; //判断操作是否合法
private JLabel stuno = new JLabel("计算器"); //学号
private JLabel stuname = new JLabel("计算器"); //姓名
public Calculator()
{
super("Calculator");
this.setBounds(300, 300, 300, 320);
this.setResizable(false);
this.setBackground(Color.orange);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.getContentPane().setLayout(new BorderLayout());//设置布局
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(stuno,BorderLayout.WEST);
topPanel.add(stuname,BorderLayout.EAST);
text_double=new JTextField("0",20);//设置文本区
text_double.setHorizontalAlignment(JTextField.RIGHT);//设置水平对齐方式未右对齐
topPanel.add(text_double,BorderLayout.SOUTH);
this.getContentPane().add(topPanel,BorderLayout.NORTH);//将文本区添加到Content北部

JPanel panel=new JPanel(new GridLayout(5,4));//在内容窗口添加一个网格布局
this.getContentPane().add(panel);//添加panel面板
for(int i=0;i panel.add(button[i]);

for(int i=0;i button[i].addActionListener(this);//为按钮注册
text_double.setEditable(false);//文本框不可编辑
text_double.addActionListener(this);//

this.setVisible(true);
}
public void actionPerformed(ActionEvent e)//
{
String c= e.getActionCommand();//返回与此动作相关的命令字符串。
System.out.println("##########command is "+c);
if(c.equals("C")){
handleC(); //用户按了“C”键
}
else if (c.equals("CE")) // 用户按了"CE"键
{
text_double.setText("0");
}
else if ("0123456789.".indexOf(c) >= 0) // 用户按了数字键或者小数点键
{
handleNumber(c); // handlezero(zero);
} else //用户按了运算符键
{
handleOperator(c);
}
}
private void handleC() // 初始化计算器的各种值
{
text_double.setText("0");
firstDigit = true;
operator = "=";
}
private void handleNumber(String button) {
if (firstDigit)//输入的第一个数字
{
text_double.setText(button);
} else if ((button.equals(".")) && (text_double.getText().indexOf(".") < 0))//输入的是小数点,并且之前没有小数点,则将小数点附在结果文本框的后面
//如果字符串参数作为一个子字符串在此对象中出现,则返回第一个这种子字符串的第一个字符的索引;如果它不作为一个子字符串出现,则返回 -1
{
text_double.setText(text_double.getText() + ".");
} else if (!button.equals("."))// 如果输入的不是小数点,则将数字附在结果文本框的后面
{
text_double.setText(text_double.getText() + button);
}
// 以后输入的肯定不是第一个数字了
firstDigit = false;
}
private void handleOperator(String button) {

if (operator.equals("/")) {
// 除法运算
// 如果当前结果文本框中的值等于0
if (getNumberFromText() == 0.0){
// 操作不合法
operateValidFlag = false;
text_double.setText("除数不能为零");
} else {
resultNum /= getNumberFromText();
}
} else if (operator.equals("+")){
// 加法运算
resultNum += getNumberFromText();
} else if (operator.equals("-")){
// 减法运算
resultNum -= getNumberFromText();
} else if (operator.equals("*")){
// 乘法运算
resultNum *= getNumberFromText();
} else if (operator.equals("sqrt")) {
// 平方根运算
if(getNumberFromText()<0){
operateValidFlag = false;
text_double.setText("被开方数不能为负数");}
else
resultNum = Math.sqrt(resultNum);
}
else if (operator.equals("+/-")){
// 正数负数运算
resultNum = resultNum * (-1);
} else if (operator.equals("=")){
// 赋值运算
resultNum = getNumberFromText();
}
if (operateValidFlag) {
// 双精度浮点数的运算
long t1;
double t2;
t1 = (long) resultNum;
t2 = resultNum - t1;
if (t2 == 0) {
text_double.setText(String.valueOf(t1));
} else {
text_double.setText(String.valueOf(resultNum));
}
}
operator = button; //运算符等于用户按的按钮
firstDigit = true;
operateValidFlag = true;
}
private double getNumberFromText() //从结果的文本框获取数字
{
double result = 0;
try {
result = Double.valueOf(text_double.getText()).doubleValue(); // ValueOf()返回表示指定的 double 值的 Double 实例
} catch (NumberFormatException e){
}
return result;
}
public static void main(final String[] args) {
new Calculator();
}
}

回答2:

支持连续运算得

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class Calculator {

public static void main(String[] args) {
Frame f = new Frame("Calculator");

final TextField tf = new TextField();
Panel p = new Panel();

f.setLayout(new BorderLayout());
f.add(tf, BorderLayout.NORTH);
f.add(p, BorderLayout.CENTER);

p.setLayout(new GridLayout(4, 4));

Button one = new Button("1");
Button two = new Button("2");
Button three = new Button("3");
Button four = new Button("4");
Button five = new Button("5");
Button six = new Button("6");
Button seven = new Button("7");
Button eight = new Button("8");
Button nine = new Button("9");
Button zero = new Button("0");
Button add = new Button("+");
Button sub = new Button("-");
Button mul = new Button("*");
Button div = new Button("/");
Button decimal = new Button(".");
final Button equal = new Button("=");

p.add(one);
p.add(two);
p.add(three);
p.add(four);
p.add(five);
p.add(six);
p.add(seven);
p.add(eight);
p.add(nine);
p.add(zero);
p.add(add);
p.add(sub);
p.add(mul);
p.add(div);
p.add(decimal);
p.add(equal);

final String[] ary = {"", null, ""};

class NumMouseListener implements MouseListener{

public void mouseClicked(MouseEvent e) {
String num = ((Button)e.getSource()).getLabel().trim();
if(ary[1] == null){
ary[0] = ary[0] + "" + num;
}else{
ary[2] = ary[2] + "" + num;
}

tf.setText(tf.getText() + "" + num);
}

public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

}

one.addMouseListener(new NumMouseListener());
two.addMouseListener(new NumMouseListener());
three.addMouseListener(new NumMouseListener());
four.addMouseListener(new NumMouseListener());
five.addMouseListener(new NumMouseListener());
six.addMouseListener(new NumMouseListener());
seven.addMouseListener(new NumMouseListener());
eight.addMouseListener(new NumMouseListener());
nine.addMouseListener(new NumMouseListener());
zero.addMouseListener(new NumMouseListener());

class OperatotrMouseListener implements MouseListener{

public void mouseClicked(MouseEvent e) {
if(e.getSource() == equal){
try {
long result = calculate(Integer.parseInt(ary[0]), Integer.parseInt(ary[2]), ary[1]);
tf.setText(String.valueOf(result));

ary[0] = tf.getText();
ary[1] = null;
ary[2] = "";
} catch (Exception e1) {
e1.printStackTrace();
}
}else{
ary[1] = ((Button) e.getSource()).getLabel();

if(ary[0].length() > 0){
ary[2] = "";
}else{
ary[0] = String.valueOf(tf.getText());
}

tf.setText("");
}
}

private long calculate(int i, int j, String operator) throws Exception {
if(operator.equals("+")){
return i + j;
}else if(operator.equals("-")){
return i - j;
}else if(operator.equals("*")){
return i * j;
}else if(operator.equals("/")){
return i / j;
}else{
throw new Exception("Invalid operator.(Only +-/* accepted");
}
}

public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}

add.addMouseListener(new OperatotrMouseListener());
mul.addMouseListener(new OperatotrMouseListener());
div.addMouseListener(new OperatotrMouseListener());
sub.addMouseListener(new OperatotrMouseListener());
equal.addMouseListener(new OperatotrMouseListener());

f.addWindowListener(new WindowListener(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}

public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
});

f.setVisible(true);
f.setBounds(200, 200, 250, 250);
f.validate();
}

}

回答3:

以前写的一个,带C得 import java.awt.BorderLayout; import java.awt.//计算器面板 private JFrame f = //加减乘除面板 private JPanel ,usojUw

回答4:

java.swing 框架,百度一下不难
虽然是个比较烂的图形框架