具体代码如下:
凤城网站建设公司创新互联,凤城网站设计制作,有大型网站制作公司丰富经验。已为凤城1000+提供企业网站建设服务。企业网站搭建\成都外贸网站制作要多少钱,请找那个售后服务好的凤城做网站的公司定做!
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Calculator extends JFrame implements ActionListener {
private JFrame jf;
private JButton[] allButtons;
private JButton clearButton;
private JTextField jtf;
public Calculator() {
//对图形组件实例化
jf=new JFrame("任静的计算器1.0:JAVA版");
jf.addWindowListener(new WindowAdapter(){
public void windowClosing(){
System.exit(0);
}
});
allButtons=new JButton[16];
clearButton=new JButton("清除");
jtf=new JTextField(25);
jtf.setEditable(false);
String str="123+456-789*0.=/";
for(int i=0;iallButtons.length;i++){
allButtons[i]=new JButton(str.substring(i,i+1));
}
}
public void init(){
//完成布局
jf.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(jtf);
for(int i=0;i16;i++){
centerPanel.add(allButtons[i]);
}
southPanel.add(clearButton);
jf.add(northPanel,BorderLayout.NORTH);
jf.add(centerPanel,BorderLayout.CENTER);
jf.add(southPanel,BorderLayout.SOUTH);
addEventHandler();
}
//添加事件监听
public void addEventHandler(){
jtf.addActionListener(this);
for(int i=0;iallButtons.length;i++){
allButtons[i].addActionListener(this);
}
clearButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Calculator.this.jtf.setText("");
}
});
}
//事件处理
public void actionPerformed(ActionEvent e) {
//在这里完成事件处理 使计算器可以运行
String action=e.getActionCommand();
if(action=="+"||action=="-"||action=="*"||action=="/"){
}
}
public void setFontAndColor(){
Font f=new Font("宋体",Font.BOLD,24);
jtf.setFont(f);
jtf.setBackground(new Color(0x8f,0xa0,0xfb));
for(int i=0;i16;i++){
allButtons[i].setFont(f);
allButtons[i].setForeground(Color.RED);
}
}
public void showMe(){
init();
setFontAndColor();
jf.pack();
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args){
new Calculator().showMe();
}
}
学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.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
class CalculatorPanel extends JPanel {
private JPanel jp; // 中间的面板
private double result; // 计算结果
private boolean start; // 用于判断是否是首次输入,true首次,false不是首次
private boolean flag; // 用于判断是否清空显示区域的值,true需要,false不需要
private String lastCommand; // 用于保存运算符
JButton display; // 显示区域
public CalculatorPanel() {
// 初始化各项值
result = 0;
start = true;
flag = false;
lastCommand = "=";
// 设置CalculatorPanel这个面板的布局为框架布局
setLayout(new BorderLayout());
// 这个按钮用来显示值的区域
display = new JButton("0.0");
display.setEnabled(false);// 按钮样式设置为禁用样式
// 用来初始化,清除用的
JButton clear = new JButton("clear");
clear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 作初始化的操作
result = 0;
start = true;
flag = false;
lastCommand = "=";
display.setText("0.0");
}
});
jp = new JPanel();
// 将此面板布局设置为网格布局,4行4列
jp.setLayout(new GridLayout(4, 4));
// 实例化监听器对象
NumberAction na = new NumberAction();
CommandAction ca = new CommandAction();
makeButton("7", na);
makeButton("8", na);
makeButton("9", na);
makeButton("/", ca);
makeButton("4", na);
makeButton("5", na);
makeButton("6", na);
makeButton("*", ca);
makeButton("1", na);
makeButton("2", na);
makeButton("3", na);
makeButton("-", ca);
makeButton("0", na);
makeButton(".", na);
makeButton("+", ca);
makeButton("=", ca);
// 将面板,两个按键加入到我的面板,实现计算器的界面
add(display, BorderLayout.NORTH);
add(jp, BorderLayout.CENTER);
add(clear, BorderLayout.SOUTH);
}
private void makeButton(String buttonName, ActionListener al) {
JButton jb = new JButton(buttonName);
jp.add(jb);
jb.addActionListener(al);
}
// 数字监听器
private class NumberAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton jb = (JButton) e.getSource(); // 获取事件源对象
String input = jb.getText(); // 获取事件源对象上的标签
if (start) { // 首次输入
// 一上就".",就什么也不做
if (input.equals(".")) {
return;
}
// 如果是"0.0"的话,就清空
if (display.getText().equals("0.0")) {
display.setText("");
}
start = false;// 改变是否首次输入的标记值
} else {
// 判断显示区域的值里面是否已经有".",如果有,输入的又是".",就什么都不做
if (display.getText().indexOf(".") != -1) {
if (input.equals(".")) {
return;
}
}
// 判断显示区域的值里面只有"-",输入的又是".",就什么都不做
if (display.getText().equals("-")) {
if (input.equals(".")) {
return;
}
}
// 判断显示区域的值如果是"0",输入的不是".",就什么也不做
if (display.getText().equals("0")) {
if (!input.equals(".")) {
return;
}
}
}
// 如果我点击了运算符以后,再输入数字的话,就要清空显示区域的值
if (flag) {
display.setText("");
flag = false;// 还原初始值,不需要清空
}
display.setText(display.getText() + input);// 设置显示区域的值
}
}
// 运算符监听器
private class CommandAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton jb = (JButton) e.getSource(); // 获取事件源对象
String inputCommand = jb.getText(); // 获取事件源对象上的标签
if (start) {// 首次输入
// 一上就是"-"
if (inputCommand.equals("-")) {
display.setText("-");// 显示区域的内容设置为"-"
start = false;// 改变首次输入的标记
}
} else {
if (!flag) {// 如果flag=false不需要清空显示区的值,就调用方法计算
calculate(Double.parseDouble(display.getText()));// 保存显示区域的值,并计算
}
// 保存你点击的运算符
lastCommand = inputCommand;
flag = true;// 因为我这里已经输入过运算符,
}
}
}
// 计算用的方法
private 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;
}
display.setText("" + result);
}
}
class MyFrameUitl {
public static void init(JFrame jFrame, Dimension frameSize, String title,
String iconFileName, boolean resizable) {
Toolkit tk = Toolkit.getDefaultToolkit(); // 系统工具包,可以读取系统信息
Dimension screenSize = tk.getScreenSize();// 获取屏幕大小
// 获取宽高
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
// 找中心点
int centerX = screenWidth / 2;
int centerY = screenHeight / 2;
// 解析窗体大小
int frameWidth = frameSize.width;
int frameHeight = frameSize.height;
// 设置窗体位置
jFrame.setBounds(centerX - frameWidth / 2, centerY - frameHeight / 2,
frameWidth, frameHeight);
jFrame.setTitle(title);// 设置标题
if (iconFileName != null) {
jFrame.setIconImage(tk.getImage(iconFileName));// 设置图标
}
// 设置皮肤com.sun.java.swing.plaf.windows.WindowsLookAndFeel
/**/
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI(jFrame);
} catch (Exception e1) {
e1.printStackTrace();
}
jFrame.setResizable(resizable);// 设置窗体是否可以改变大小
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置程序关闭动作
jFrame.setVisible(true);// 显示窗体
}
}
class CalculatorFrame extends JFrame {
public CalculatorFrame() {
add(new CalculatorPanel());
MyFrameUitl.init(this, new Dimension(400, 300), "简易计算器", null,
false);
this.pack();// 让组件按原始大小显示,并且窗体的大小刚好能够容纳所有的组件
}
}
public class CalculatorTest {
public static void main(String[] args) {
new CalculatorFrame();
}
}
运行效果:
/*
* @(#)JCalculator.java 1.00 06/17/2015
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* A simple calculator program.
* pI saw this program in a QQ group, and help a friend correct it./p
*
* @author Singyuen Yip
* @version 1.00 12/29/2009
* @see JFrame
* @see ActionListener
*/
public class JCalculator extends JFrame implements ActionListener {
/**
* Serial Version UID
*/
private static final long serialVersionUID = -169068472193786457L;
/**
* This class help close the Window.
* @author Singyuen Yip
*
*/
private class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
int i;
// Strings for Digit Operator buttons.
private final String[] str = { "7", "8", "9", "/", "4", "5", "6", "*","1",
"2", "3", "-", ".", "0", "=", "+" };
// Build buttons.
JButton[] buttons = new JButton[str.length];
// For cancel or reset.
JButton reset = new JButton("CE");
// Build the text field to show the result.
JTextField display = new JTextField("0");
/**
* Constructor without parameters.
*/
public JCalculator() {
super("Calculator");
// Add a panel.
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);
// 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(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 ("0123456789.".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 = "=";
/**
* Handling the operation.
* @param key pressed operator's key.
*/
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();
}
}
运行界面:
有一个现成的.你看看吧
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");
}
}
}
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可以直接运行了