JAVA实现四则运算的简单计算器,带时分秒选择功能
分类:高并发

import java.awt.event.ActionEvent;

开发环境eclipse java neon.

DateSelector.java

import java.awt.BorderLayout; import java.awt.GridBagLayout; 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; public class Calculator extends JFrame implements ActionListener {   JTextField result;   int calculate_type=0;   Calculator(){    JPanel jp;  JButton jb;  jp= new JPanel();  jp.setLayout(new BorderLayout());  result = new JTextField();  result.setEditable(false);  jp.add(result,BorderLayout.NORTH);//窗口中间添加数字按钮、清空、退格、小数点按钮    JPanel keyPanel = new JPanel();  keyPanel.setLayout(new GridLayout(5,3));  jb = new JButton("1");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("2");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("3");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("4");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("5");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("6");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("7");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("8");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("9");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("0");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("C");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("退格");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton(".");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("=");  keyPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("CE");  keyPanel.add(jb);  jb.addActionListener(this);  jp.add(keyPanel,BorderLayout.CENTER);  JPanel operatorpJPanel = new JPanel();  operatorpJPanel.setLayout(new GridLayout(4,1));  jb = new JButton("+");  operatorpJPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("-");  operatorpJPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("*");  operatorpJPanel.add(jb);  jb.addActionListener(this);  jb = new JButton("/");  operatorpJPanel.add(jb);  jb.addActionListener(this);  jp.add(operatorpJPanel,BorderLayout.EAST);  setContentPane(jp);  setTitle("计算器");  setSize(340,260);  setVisible(true);  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   }      public void  actionPerformed(ActionEvent e){     String cmd =e.getActionCommand();     String c =result.getText();     if (cmd.equals("C")) { result.setText(""); }     else if (cmd.equals("退格")) { if (c.length()>0) { String slast = c.substring(c.length() -1); if (slast.equals("+") || slast.equals("-") || slast.equals("*")  || slast.equals("/")) { calculate_type = 0;//如果删除了运算符,将计算类型恢复为未确定状态 } result.setText(c.substring(0,c.length() -1)); } else if (cmd.compareTo("0")>=0 && cmd.compareTo("9")<=0) { result.setText(c+cmd); } else if (cmd.equals(".")) { result.setText(c+cmd); } else if (cmd.equals("+") || cmd.equals("-") || cmd.equals("*") || cmd.equals("/") ) { if (calculate_type ==0) { result.setText(c+cmd); judgeCalculateType(cmd);//判断计算类型 } else {//自上次计算完成后,第二次点击运算符,触发计算 calculate(); result.setText(result.getText()+cmd); judgeCalculateType(cmd);//判断计算类型 } } else if (cmd.equals("=")) {//点击=进行计算 try { } catch (Exception exp) { JOptionPane.showMessageDialog(this, "输入错误,请检查输出或重新启动程序"); } } }      }    //判断计算类型 private void judgeCalculateType(String cmd) {     if (cmd.equals("+"))  calculate_type =1;//记录运算类型 else if (cmd.equals("-"))  calculate_type =2; else if(cmd.equals("*")) calculate_type =3; else calculate_type =4; } //完成计算功能    private void calculate() { double rt,op1,op2; String c = result.getText(); int pos; char ops[] ={'+','-','*','/'};//查找运算符位置 pos =c.indexOf(ops[calculate_type-1]);//以运算符位置为分界点,分离出两个待计算的数 op1 = Double.parseDouble(c.substring(0,pos));     op2 = Double.parseDouble(c.substring(pos+1));     switch (calculate_type) { case 1: rt = op1+op2; break; case 2: rt = op1-op2; break; case 3: rt = op1*op2; break; case 4: rt = op1/op2; break; default:  rt =0; }     result.setText("" +rt);//显示计算结果     calculate_type =0;//准备记录下次计算的类型 } public static void main(String[] args) { new Calculator(); } }

import java.awt.event.ActionListener;

今天用JAVA的swing界面程序设计制作了一个四则运算的简易计算器.代码以及截图如下:

package Test;

import javax.swing.JButton;

computer.java:

import java.util.Date;

import javax.swing.JFrame;

/////////////////////////////////////////
//
//开发者:
//
//简介:实现四则运算的简易计算器
//
////////////////////////////////////////
/*
*用swing图形用户界面实现计算器的设计
*同时练习在线文档注释的使用方法
*
* @author linruier
* @version 1.0
* @since J2SE1.8
*/
import javax.swing.JButton;
import java.awt.Graphics;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JPanel;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class computer extends JFrame
{
computer()
{
super("简易计算器");
Font f=new Font("黑体",30,30);
JTextField jt1=new JTextField(null);
JTextField jt2=new JTextField(null);
jt1.setFont(f);
jt2.setFont(f);
jt1.setHorizontalAlignment(JTextField.RIGHT);
jt2.setHorizontalAlignment(JTextField.RIGHT);
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
c.add(jt1);
c.add(jt2);
jt1.setPreferredSize(new Dimension(370,70));
jt2.setPreferredSize(new Dimension(370,75));
jt1.setEditable(false);jt2.setEditable(false);
JButton jb[]=new JButton[16];
for(int j=0;j<16;j++)
{
jb[j]=new JButton();
jb[j].setBackground(Color.WHITE);
jb[j].setFocusable(false);
jb[j].setPreferredSize(new Dimension(90,90));
jb[j].setFont(f);
c.add(jb[j]);
}
this.setResizable(false);
//对各个按钮的名称赋值
jb[0].setText("+");jb[1].setText("-");jb[2].setText("*");jb[3].setText("/");
jb[4].setText("1");jb[5].setText("2");jb[6].setText("3");jb[7].setText("C");jb[7].setBackground(Color.ORANGE);
jb[8].setText("4");jb[9].setText("5");jb[10].setText("6");jb[11].setText("0");
jb[12].setText("7");jb[13].setText("8");jb[14].setText("9");jb[15].setText("=");

import java.util.Calendar;

import javax.swing.JTextField;

JButton Button_num[]={jb[4],jb[5],jb[6],jb[8],jb[9],jb[10],jb[11],jb[12],jb[13],jb[14]};
for(int i=0;i<Button_num.length;i++)
{
Button_num[i].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JButton action_Button=(JButton)e.getSource();
jt2.setText(jt2.getText()+action_Button.getText());
}
}
);
}
for(int j=0;j<4;j++)
{
jb[j].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String s=jt2.getText();
char ch=s.charAt(s.length()-1);

import java.text.DateFormat;

class Stack_Float 

if(ch=='+'||ch=='-'||ch=='*'||ch=='/')((JButton)e.getSource()).setEnabled(false);
else
{
jt1.setText(jt2.getText());
jt2.setText(((JButton)e.getSource()).getText());
}

import java.text.SimpleDateFormat;

{

}
}
);
}
jb[7].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
jt1.setText(null);jt2.setText(null);
}
}

import java.text.ParseException;

 float nums[];

);
jb[15].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
String Calculate_String=jt1.getText()+jt2.getText();
int result=calculation.result(Calculate_String);
jt1.setText(null);
jt2.setText(Integer.toString(result));
}
catch(ArithmeticException ex)
{
jt1.setText(null);jt2.setText("ERROR");
}
}
}
);
}
public static void main(String args[])
{
computer app=new computer();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize(400,580);
app.setVisible(true);
}
}

import java.awt.Color;

 int top;

 

import java.awt.Font;

 Stack_Float() 

 

import java.awt.Point;

 {

//再定义一个计算类calculation.java:

import java.awt.Dimension;

  nums = new float[50];

public class calculation {
calculation(){};
boolean is_operator(char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/')return true;
else return false;
}
static int result(String s)
{
String ch[]={"+","-","*","/"};
int i=0;int index;
while(s.indexOf(ch[i])==-1&&i<4){i++;}
if(i==4)return -1;
else index=s.indexOf(ch[i]);
String s1=s.substring(0, index);
String s2=s.substring(index+1, s.length());
if(i==0)return Integer.parseInt(s1)+Integer.parseInt(s2);
if(i==1)return Integer.parseInt(s1)-Integer.parseInt(s2);
if(i==2)return Integer.parseInt(s1)*Integer.parseInt(s2);
if(i==3&&Integer.parseInt(s2)!=0)return Integer.parseInt(s1)/Integer.parseInt(s2);
else if(i==3&&Integer.parseInt(s2)==0){throw new ArithmeticException();}
return -1;
}

import java.awt.BorderLayout;

  top = -1;

}

import java.awt.FlowLayout;

 }

最后运行就可以实现一个十分简洁的小计算器:

import java.awt.GridLayout;

 boolean IsEmpty() 

图片 1

import java.awt.Component;

 {

图片 2

import java.awt.Cursor;

  if (top == -1)

图片 3

import java.awt.Frame;

   return true;

 

import java.awt.event.ActionEvent;

  else

import java.awt.event.ActionListener;

   return false;

import java.awt.event.MouseListener;

 }

import java.awt.event.MouseAdapter;

 float Pop_Stack() 

import java.awt.event.MouseEvent; //import javax.swing.JFrame;

 {

import javax.swing.JButton;

  if (top == -1) 

import javax.swing.JDialog;

  {

import javax.swing.JPanel;

   return 0;

import javax.swing.JLabel;

  }

import javax.swing.JSpinner;

  top--;

import javax.swing.JSpinner.NumberEditor;

  return nums[top + 1];

import javax.swing.SpinnerNumberModel;

 }

import javax.swing.SwingUtilities;

 float GetTop() 

import javax.swing.SwingConstants;

 {

import javax.swing.event.ChangeListener;

  return nums[top];

import javax.swing.event.ChangeEvent;

 }

import javax.swing.border.LineBorder;

 void Push_Stack(float num) 

public class DateSelector extends JButton {

 {

private DateChooser dateChooser = null;

  if (top == 49)

private String preLabel = "";

   return;

public DateSelector() {

  top++;

this(getNowDate());

  nums[top] = num;

}

 }

public DateSelector(SimpleDateFormat df, String dateString) {

}

this();

class Stack_Char 

setText(df, dateString);

{

}

 char str[];

public DateSelector(Date date) {

 int top;

this("", date);

 Stack_Char() 

}

 {

public DateSelector(String preLabel, Date date) {

  str = new char[50];

if (preLabel != null)

  top = -1;

this.preLabel = preLabel;

 }

setDate(date);

 boolean CanPush(char c) 

setBorder(null);

 {

setCursor(new Cursor(Cursor.HAND_CURSOR));

  int temp = top;

super.addActionListener(new ActionListener() {

  if (c == '(') 

public void actionPerformed(ActionEvent e) {

  {

if (dateChooser == null)

   while (temp != -1) 

dateChooser = new DateChooser();

   {

Point p = getLocationOnScreen();

    if (str[temp] == '(')

p.y = p.y + 30;

    {

dateChooser.showDateChooser(p);

     return false;

}

    }

});

    temp--;

}

   }

private static Date getNowDate() {

  }

return Calendar.getInstance().getTime();

  temp = top;

}

  if (c == '[') 

private static SimpleDateFormat getDefaultDateFormat() {

  {

return new SimpleDateFormat("yyyy年MM月dd日  HH时mm分ss秒");

   while (temp != -1) 

}

   {

public void setText(String s) {

    if (str[temp] == '[' || str[temp] == '(') 

Date date;

    {

try {

     return false;

date = getDefaultDateFormat().parse(s);

    }

} catch (ParseException e) {

    temp--;

date = getNowDate();

   }

}

  }

setDate(date);

  if (c == '{') 

}

  {

public void setText(SimpleDateFormat df, String s) {

   while (temp != -1) 

Date date;

   {

try {

    if (str[temp] == '{' || str[temp] == '[' || str[temp] == '(') 

date = df.parse(s);

    {

} catch (ParseException e) {

     return false;

date = getNowDate();

    }

}

    temp--;

setDate(date);

   }

}

  }

public void setDate(Date date) {

  return true;

super.setText(preLabel + getDefaultDateFormat().format(date));

 }

}

 boolean IsEmpty() 

public Date getDate() {

 {

String dateString = getText().substring(preLabel.length());

  if (top == -1)

try {

   return true;

return getDefaultDateFormat().parse(dateString);

  else

} catch (ParseException e) {

   return false;

return getNowDate();

 }

}

 void Push_Stack(char ch) 

}

 {

// 覆盖父类的方法使之无效

  if (top == 49)

public void addActionListener(ActionListener listener) {

   return;

}

  top++;

private class DateChooser extends JPanel implements ActionListener,

  str[top] = ch;

ChangeListener {

 }

int startYear = 1980; // 默认【最小】显示年份

 char Pop_Stack() 

int lastYear = 2050; // 默认【最大】显示年份

 {

int width = 200; // 界面宽度

  if (top == -1)

int height = 200; // 界面高度

   return '';

Color backGroundColor = Color.gray; // 底色

  top--;

// 月历表格配色----------------//

  return str[top + 1];

Color palletTableColor = Color.white; // 日历表底色

 }

Color todayBackColor = Color.orange; // 今天背景色

 char GetTop() 

Color weekFontColor = Color.blue; // 星期文字色

 {

Color dateFontColor = Color.black; // 日期文字色

  if (top == -1) 

Color weekendFontColor = Color.red; // 周末文字色

  {

// 控制条配色------------------//

   System.out.print("error");

Color controlLineColor = Color.blue; // 控制条底色

   System.exit(0);

Color controlTextColor = Color.white; // 控制条标签文字色

  }

Color rbFontColor = Color.white; // RoundBox文字色

  return str[top];

Color rbBorderColor = Color.red; // RoundBox边框色

 }

Color rbButtonColor = Color.pink; // RoundBox按钮色

}

Color rbBtFontColor = Color.red; // RoundBox按钮文字色

public class Jisuanqi extends javax.swing.JFrame implements ActionListener 

JDialog dialog;

{

JSpinner yearSpin;

 JTextField text = new JTextField();

JSpinner monthSpin;

 JTextField text1 = new JTextField();

JSpinner hourSpin;

 JButton jButton1 = new JButton();

JSpinner minuteSpin;

 JButton jButton2 = new JButton();

JSpinner secondSpin;

 JButton jButton3 = new JButton();

JButton[][] daysButton = new JButton[6][7];

 JButton jButton4 = new JButton();

DateChooser() {

 JButton jButton5 = new JButton();

setLayout(new BorderLayout());

 JButton jButton6 = new JButton();

setBorder(new LineBorder(backGroundColor, 2));

 JButton jButton7 = new JButton();

setBackground(backGroundColor);

 JButton jButton8 = new JButton();

/*上中下布局*/

 JButton jButton9 = new JButton();

JPanel topYearAndMonth = createYearAndMonthPanal();

 JButton jButton10 = new JButton();

add(topYearAndMonth, BorderLayout.NORTH);

 JButton jButton11 = new JButton();

JPanel centerWeekAndDay = createWeekAndDayPanal();

 JButton jButton12 = new JButton();

add(centerWeekAndDay, BorderLayout.CENTER);

 JButton jButton13 = new JButton();

JPanel southMinAndSec = createMinuteAndsecondPanal();

 JButton jButton14 = new JButton();

add(southMinAndSec, BorderLayout.SOUTH);

 JButton jButton15 = new JButton();

}

 JButton jButton16 = new JButton();

private JPanel createYearAndMonthPanal() {

 JButton jButton17 = new JButton();

Calendar c = getCalendar();

 JButton jButton18 = new JButton();

int currentYear = c.get(Calendar.YEAR);//年

 JButton jButton19 = new JButton();

int currentMonth = c.get(Calendar.MONTH) + 1;//月

 JButton jButton20 = new JButton();

JPanel result = new JPanel();

 JButton jButton21 = new JButton();

result.setLayout(new FlowLayout());

 JButton jButton22 = new JButton();

result.setBackground(controlLineColor);

 String show = "";

yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,

 public jisuanqi() 

startYear, lastYear, 1));

 {

yearSpin.setPreferredSize(new Dimension(48, 20));

  initComponents();

yearSpin.setName("Year");

 }

yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));

 char[] TranSmit(char str[]) 

yearSpin.addChangeListener(this);

 {

result.add(yearSpin);

  char houzhui[] = new char[50]; // 存放后缀表达式的字符串

JLabel yearLabel = new JLabel("年");

  int i = 0, j = 0;

yearLabel.setForeground(controlTextColor);

  char c = str[i];

result.add(yearLabel);

  Stack_Char s = new Stack_Char(); // 存放运算符的栈

monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,

  while (c != '=') // 对算术表达式扫描未结束时

12, 1));

  {

monthSpin.setPreferredSize(new Dimension(35, 20));

   if (c >= '0' && c <= '9') 

monthSpin.setName("Month");

   {

monthSpin.addChangeListener(this);

    while (c >= '0' && c <= '9')// 数字直接入栈

result.add(monthSpin);

    {

JLabel monthLabel = new JLabel("月");

     houzhui[j] = c;

monthLabel.setForeground(controlTextColor);

     j++;

result.add(monthLabel);

     i++;

return result;

     c = str[i];

}

    }

private JPanel createWeekAndDayPanal() {

    houzhui[j] = '#';// 用#隔开数字

String colname[] = { "日", "一", "二", "三", "四", "五", "六" };

    j++;

JPanel result = new JPanel();

   }

// 设置固定字体,以免调用环境改变影响界面美观

   switch (c) // 扫描到运算符时

result.setFont(new Font("宋体", Font.PLAIN, 12));

   {

result.setLayout(new GridLayout(7, 7));

   case '+':

result.setBackground(Color.white);

   case '-':

JLabel cell;

   case '*':

for (int i = 0; i < 7; i++) {

   case '/':

cell = new JLabel(colname[i]);

   case '(':

cell.setHorizontalAlignment(JLabel.RIGHT);

   case '[':

if (i == 0 || i == 6)

   case '{':

cell.setForeground(weekendFontColor);

    if (s.IsEmpty() == true) // 栈空,直接入栈

else

    {

cell.setForeground(weekFontColor);

     s.Push_Stack(c);

result.add(cell);

     i++;

}

     c = str[i];

int actionCommandId = 0;

     break;

for (int i = 0; i < 6; i++)

    }

for (int j = 0; j < 7; j++) {

    if (ComPare(s.GetTop(), c) == -1) {

JButton numberButton = new JButton();

     s.Push_Stack(c); // 入栈

numberButton.setBorder(null);

     i++;

numberButton.setHorizontalAlignment(SwingConstants.RIGHT);

     c = str[i];

numberButton.setActionCommand(String

     break;

.valueOf(actionCommandId));

    }

numberButton.addActionListener(this);

    if (ComPare(s.GetTop(), c) == 1) {

numberButton.setBackground(palletTableColor);

     houzhui[j] = s.Pop_Stack();// 出栈元素存入后缀表达式

numberButton.setForeground(dateFontColor);

     j++;

if (j == 0 || j == 6)

     break;

numberButton.setForeground(weekendFontColor);

    }

else

   case ')': // 扫描到 )

numberButton.setForeground(dateFontColor);

    while (s.GetTop() != '(') // 未扫描到 ( 时,出栈

daysButton[i][j] = numberButton;

    {

result.add(numberButton);

     houzhui[j] = s.Pop_Stack();

actionCommandId++;

     j++;

}

    }

return result;

    s.Pop_Stack(); // '(' 出栈

}

    i++;

private JPanel createMinuteAndsecondPanal() {

    c = str[i];

Calendar c = getCalendar();

    break;

int currentHour = c.get(Calendar.HOUR_OF_DAY);//时

   case ']': // 扫描到 ]

int currentMin = c.get(Calendar.MINUTE);//分

    while (s.GetTop() != '[') // 未扫描到 [ 时,出栈

int currentSec = c.get(Calendar.SECOND);//秒

    {

JPanel result = new JPanel();

     houzhui[j] = s.Pop_Stack();

result.setLayout(new FlowLayout());

     j++;

result.setBackground(controlLineColor);

    }

hourSpin = new JSpinner(new SpinnerNumberModel(currentHour, 0, 23,1));

    s.Pop_Stack(); // '[' 出栈

hourSpin.setPreferredSize(new Dimension(35, 20));

    i++;

hourSpin.setName("Hour");

    c = str[i];

hourSpin.addChangeListener(this);

    break;

result.add(hourSpin);

   case '}': // 扫描到 }

JLabel hourLabel = new JLabel("时");

    while (s.GetTop() != '{') // 未扫描到 { 时,出栈

hourLabel.setForeground(controlTextColor);

    {

result.add(hourLabel);

     houzhui[j] = s.Pop_Stack();

minuteSpin = new JSpinner(new SpinnerNumberModel(currentMin, 0, 59, 1));

     j++;

minuteSpin.setPreferredSize(new Dimension(35, 20));

    }

minuteSpin.setName("Minute");

    s.Pop_Stack(); // '{' 出栈

minuteSpin.addChangeListener(this);

    i++;

result.add(minuteSpin);

    c = str[i];

JLabel minuteLabel = new JLabel("分");

    break;

minuteLabel.setForeground(controlTextColor);

   }

result.add(minuteLabel);

  }

secondSpin = new JSpinner(new SpinnerNumberModel(currentSec, 0, 59,1));

  while (s.IsEmpty() != true)// 把剩余的运算符直接出栈

secondSpin.setPreferredSize(new Dimension(35, 20));

  {

secondSpin.setName("Second");

   houzhui[j] = s.Pop_Stack();

secondSpin.addChangeListener(this);

   j++;

result.add(secondSpin);

  }

JLabel secondLabel = new JLabel("秒");

  houzhui[j] = '=';// 后缀表达式后面加 =

secondLabel.setForeground(controlTextColor);

  j++;

result.add(secondLabel);

  houzhui[j] = '';

return result;

  j++;

}

  return houzhui;

private JDialog createDialog(Frame owner) {

 }

JDialog result = new JDialog(owner, "日期时间选择", true);

 float Count(char str[]) 

result.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);

 {

result.getContentPane().add(this, BorderLayout.CENTER);

  Stack_Float s = new Stack_Float();// 定义存放数字的栈

result.pack();

  char c = str[0];

result.setSize(width, height);

  int i = 0;

return result;

  float result = 0, temp, left, right;

}

  while (c != '=') // 未扫描到 = 时

void showDateChooser(Point position) {

  {

Frame owner = (Frame) SwingUtilities

   if (c >= '0' && c <= '9')// 扫描到数字

.getWindowAncestor(DateSelector.this);

   {

if (dialog == null || dialog.getOwner() != owner)

    temp = 0;

dialog = createDialog(owner);

    while (c != '#')// 未读到分隔符时

dialog.setLocation(getAppropriateLocation(owner, position));

    {

flushWeekAndDay();

     temp = temp * 10 + c - '0';

dialog.show();

     i++;

}

     c = str[i];

Point getAppropriateLocation(Frame owner, Point position) {

    }

Point result = new Point(position);

    s.Push_Stack(temp);// 进栈

Point p = owner.getLocation();

   }

int offsetX = (position.x + width) - (p.x + owner.getWidth());

   switch (c)// 扫描到运算符时

int offsetY = (position.y + height) - (p.y + owner.getHeight());

   {

if (offsetX > 0) {

    case '+': 

result.x -= offsetX;

    {

}

     result = s.Pop_Stack() + s.Pop_Stack();// 2个数字出栈相加

if (offsetY > 0) {

     s.Push_Stack(result);// 最后得数进栈

result.y -= offsetY;

     break;

}

    }

return result;

    case '-': 

}

    {

private Calendar getCalendar() {

     right = s.Pop_Stack();// 右操作数出栈

Calendar result = Calendar.getInstance();

     left = s.Pop_Stack();// 左操作数出栈

result.setTime(getDate());

     result = left - right;

return result;

     s.Push_Stack(result);

}

     break;

private int getSelectedYear() {

    }

return ((Integer) yearSpin.getValue()).intValue();

    case '*': 

}

    {

private int getSelectedMonth() {

     result = s.Pop_Stack() * s.Pop_Stack();// 2个数字出栈相乘

return ((Integer) monthSpin.getValue()).intValue();

     s.Push_Stack(result);

}

     break;

private int getSelectedHour() {

    }

return ((Integer) hourSpin.getValue()).intValue();

    case '/': 

}

    {

private int getSelectedMinute() {

     right = s.Pop_Stack();// 右操作数出栈

return ((Integer) minuteSpin.getValue()).intValue();

     left = s.Pop_Stack();// 左操作数出栈

}

     result = left / right;

private int getSelectedSecond() {

     s.Push_Stack(result);

return ((Integer) secondSpin.getValue()).intValue();

     break;

}

    }

private void dayColorUpdate(boolean isOldDay) {

   }

Calendar c = getCalendar();

   i++;

int day = c.get(Calendar.DAY_OF_MONTH);

   c = str[i];

c.set(Calendar.DAY_OF_MONTH, 1);

  }

int actionCommandId = day - 2 + c.get(Calendar.DAY_OF_WEEK);

  return result;

int i = actionCommandId / 7;

 }

int j = actionCommandId % 7;

 int ComPare(char a, char b) // 判断运算符的优先级函数

if (isOldDay)

 {

daysButton[i][j].setForeground(dateFontColor);

  int s[][] = {// 栈顶元素高于算术表达式中的元素时, 返回 1,否则返回 -1

else

    { 1, 1, -1, -1, -1, 1, -1, 1, -1, 1 },

daysButton[i][j].setForeground(todayBackColor);

    { 1, 1, -1, -1, -1, 1, -1, 1, -1, 1 },

}

    { 1, 1, 1, 1, -1, 1, -1, 1, -1, 1 },

private void flushWeekAndDay() {

    { 1, 1, 1, 1, -1, 1, -1, 1, -1, 1 },

Calendar c = getCalendar();

    { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 },

c.set(Calendar.DAY_OF_MONTH, 1);

    { 1, 1, 1, 1, -1, 1, -1, -1, -1, -1 },

int maxDayNo = c.getActualMaximum(Calendar.DAY_OF_MONTH);

    { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 },

int dayNo = 2 - c.get(Calendar.DAY_OF_WEEK);

    { 1, 1, 1, 1, -1, -1, -1, -1, -1, 1 },

for (int i = 0; i < 6; i++) {

    { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 },

for (int j = 0; j < 7; j++) {

    { 1, 1, 1, 1, -1, -1, -1, -1, -1, -1 } };

String s = "";

  char x1[] = { '+', '-', '*', '/', '(', ')', '[', ']', '{', '}' };// 栈顶元素

if (dayNo >= 1 && dayNo <= maxDayNo)

  char x2[] = { '+', '-', '*', '/', '(', ')', '[', ']', '{', '}' };// 算术表达式中的元素

s = String.valueOf(dayNo);

  int k = 0, m, n = 0;

daysButton[i][j].setText(s);

  for (m = 0; m < 10; m++) // 查找2个进行比较的运算符在表中的位置,并返回比较结果

dayNo++;

  {

}

   for (n = 0; n < 10; n++) 

}

   {

dayColorUpdate(false);

    if (x1[m] == a && x2[n] == b) 

}

    {

public void stateChanged(ChangeEvent e) {

     k = 1;

JSpinner source = (JSpinner) e.getSource();

     break; // 找到比较结果后,跳出循环

Calendar c = getCalendar();

    }

if (source.getName().equals("Hour")) {

   }

c.set(Calendar.HOUR_OF_DAY, getSelectedHour());

   if (k == 1)

setDate(c.getTime());

    break;

return;

  }

}

  return s[m][n];// 返回比较结果

else if(source.getName().equals("Minute")){

 }

c.set(Calendar.MINUTE, getSelectedMinute());

 public void actionPerformed(ActionEvent e) 

setDate(c.getTime());

 {

return;

  if (e.getSource() == jButton1) 

}

  {

else if(source.getName().equals("Second")){

   show += "1";

c.set(Calendar.SECOND, getSelectedSecond());

   text.setText(show);

setDate(c.getTime());

  }

return;

  if (e.getSource() == jButton2) 

}

  {

dayColorUpdate(true);

   show += "2";

if (source.getName().equals("Year"))

   text.setText(show);

c.set(Calendar.YEAR, getSelectedYear());

  }

else

  if (e.getSource() == jButton3) 

// (source.getName().equals("Month"))

  {

c.set(Calendar.MONTH, getSelectedMonth() - 1);

   show += "3";

setDate(c.getTime());

   text.setText(show);

flushWeekAndDay();

  }

}

  if (e.getSource() == jButton4) 

public void actionPerformed(ActionEvent e) {

  {

JButton source = (JButton) e.getSource();

   show += "4";

if (source.getText().length() == 0)return;

   text.setText(show);

dayColorUpdate(true);

  }

source.setForeground(todayBackColor);

  if (e.getSource() == jButton5) 

int newDay = Integer.parseInt(source.getText());

  {

Calendar c = getCalendar();

   show += "5";

c.set(Calendar.DAY_OF_MONTH, newDay);

   text.setText(show);

setDate(c.getTime());

  }

}

  if (e.getSource() == jButton6) 

}

  {

}

   show += "6";

==========================================================================

   text.setText(show);

Test.java

  }

package Test;

  if (e.getSource() == jButton7) 

import java.awt.BorderLayout;

  {

import java.awt.EventQueue;

   show += "7";

import javax.swing.JFrame;

   text.setText(show);

import javax.swing.JPanel;

  }

import javax.swing.border.EmptyBorder;

  if (e.getSource() == jButton8) 

import javax.swing.JButton;

  {

public class Test extends JFrame {

   show += "8";

private JPanel contentPane;

   text.setText(show);

public static void main(String[] args) {

  }

Test frame = new Test();

  if (e.getSource() == jButton9) 

frame.setVisible(true);

  {

}

   show += "9";

public Test() {

   text.setText(show);

setBounds(100, 100, 350, 200);

  }

contentPane = new JPanel();

  if (e.getSource() == jButton10) 

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

  {

contentPane.setLayout(new BorderLayout(0, 0));

   show += "0";

setContentPane(contentPane);

   text.setText(show);

JButton button = new DateSelector();

  }

contentPane.add(button, BorderLayout.CENTER);

  if (e.getSource() == jButton11) 

}

  {

}

   show += "+";

============================         我是分割线   ==============================

   text.setText(show);

点击Test.java类,点击Run as 运行程序后,效果如下图所示:

  }

图片 4

  if (e.getSource() == jButton12) 

  {

   show += "-";

   text.setText(show);

  }

  if (e.getSource() == jButton13) 

  {

   show += "*";

   text.setText(show);

  }

  if (e.getSource() == jButton14) 

  {

   show += "/";

   text.setText(show);

  }

  if (e.getSource() == jButton15) 

  {

   show += "(";

   text.setText(show);

  }

  if (e.getSource() == jButton16) 

  {

   show += ")";

   text.setText(show);

  }

  if (e.getSource() == jButton17) 

  {

   show += "[";

   text.setText(show);

  }

  if (e.getSource() == jButton18) 

  {

   show += "]";

   text.setText(show);

  }

  if (e.getSource() == jButton19) 

  {

   show += "{";

   text.setText(show);

  }

  if (e.getSource() == jButton20) 

  {

   show += "}";

   text.setText(show);

  }

  if (e.getSource() == jButton21) 

  {

   show = "";

   text.setText("");

   text1.setText("");

  }

  if (e.getSource() == jButton22) 

  {

   show += "=";

   text.setText(show);

   char str1[] = new char[50];

   char str2[] = new char[50];

   float result = 0;

   str1 = show.toCharArray();

   str2 = TranSmit(str1);

   result = Count(str2);

   text1.setText((new String(str2)).trim());

   text.setText("" + result);

   show = "";

  }

 }

 private void initComponents() 

 {

  text.setBounds(10, 10, 270, 30);

  text1.setBounds(10, 50, 270, 30);

  jButton1.setBounds(10, 90, 60, 25);

  jButton2.setBounds(80, 90, 60, 25);

  jButton3.setBounds(150, 90, 60, 25);

  jButton4.setBounds(220, 90, 60, 25);

  jButton5.setBounds(10, 120, 60, 25);

  jButton6.setBounds(80, 120, 60, 25);

  jButton7.setBounds(150, 120, 60, 25);

  jButton8.setBounds(220, 120, 60, 25);

  jButton9.setBounds(10, 150, 60, 25);

  jButton10.setBounds(80, 150, 60, 25);

  jButton11.setBounds(150, 150, 60, 25);

  jButton12.setBounds(220, 150, 60, 25);

  jButton13.setBounds(10, 180, 60, 25);

  jButton14.setBounds(80, 180, 60, 25);

  jButton15.setBounds(150, 180, 60, 25);

  jButton16.setBounds(220, 180, 60, 25);

  jButton17.setBounds(150, 210, 60, 25);

  jButton18.setBounds(220, 210, 60, 25);

  jButton19.setBounds(10, 210, 60, 25);

  jButton20.setBounds(80, 210, 60, 25);

  jButton21.setBounds(10, 240, 60, 25);

  jButton22.setBounds(80, 240, 60, 25);

  jButton1.setText("1");

  jButton2.setText("2");

  jButton3.setText("3");

  jButton4.setText("4");

  jButton5.setText("5");

  jButton6.setText("6");

  jButton7.setText("7");

  jButton8.setText("8");

  jButton9.setText("9");

  jButton10.setText("0");

  jButton11.setText("+");

  jButton12.setText("-");

  jButton13.setText("*");

  jButton14.setText("/");

  jButton15.setText("(");

  jButton16.setText(")");

  jButton17.setText("[");

  jButton18.setText("]");

  jButton19.setText("{");

  jButton20.setText("}");

  jButton21.setText("CE");

  jButton22.setText("=");

  jButton1.addActionListener(this);

  jButton2.addActionListener(this);

  jButton3.addActionListener(this);

  jButton4.addActionListener(this);

  jButton5.addActionListener(this);

  jButton6.addActionListener(this);

  jButton7.addActionListener(this);

  jButton8.addActionListener(this);

  jButton9.addActionListener(this);

  jButton10.addActionListener(this);

  jButton11.addActionListener(this);

  jButton12.addActionListener(this);

  jButton13.addActionListener(this);

  jButton14.addActionListener(this);

  jButton15.addActionListener(this);

  jButton16.addActionListener(this);

  jButton17.addActionListener(this);

  jButton18.addActionListener(this);

  jButton19.addActionListener(this);

  jButton20.addActionListener(this);

  jButton21.addActionListener(this);

  jButton22.addActionListener(this);

  

  add(text);

  add(text1);

  add(jButton1);

  add(jButton2);

  add(jButton3);

  add(jButton4);

  add(jButton5);

  add(jButton6);

  add(jButton7);

  add(jButton8);

  add(jButton9);

  add(jButton10);

  add(jButton11);

  add(jButton12);

  add(jButton13);

  add(jButton14);

  add(jButton15);

  add(jButton16);

  add(jButton17);

  add(jButton18);

  add(jButton19);

  add(jButton20);

  add(jButton21);

  add(jButton22);

  

  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  setLayout(null);

  setBounds(300, 300, 300, 300);

  setVisible(true);

 }

 public static void main(String args[]) 

 {

  new Jisuanqi();

 }

}

/*<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

 <HEAD>

  <TITLE> New Document </TITLE>

  <META NAME="Generator" CONTENT="EditPlus">

  <META NAME="Author" CONTENT="">

  <META NAME="Keywords" CONTENT="">

  <META NAME="Description" CONTENT="">

 </HEAD>

 <BODY>

  <APPLET  CODE="Jisuanji.class"  HEIGHT=450 WIDTH=450></APPLET>

 </BODY>

</HTML>

*/

本文由10bet手机官网发布于高并发,转载请注明出处:JAVA实现四则运算的简单计算器,带时分秒选择功能

上一篇:顺序程序设计,循环结构程序设计 下一篇:我为我感到自豪,我2010年工作感想
猜你喜欢
热门排行
精彩图文