java计算器程序代码
java计算器代码
delete.add(c);
delete.add(ce);
delete.setBorder(new LineBorder(delete.getBackground(), 5));//添加边框
c.addActionListener(this);
JPanel buttons = new JPanel();
JTextField text = new JTextField("0");
JButton backspace = new JButton("Backspace");
JButton c = new JButton("C");
m=0;n=1;a=0; //n=1,记录按了一个数字键,并将m还原成0,方便下次按运算符时判断
}
if(e.getSource()==bt2)
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.text.*;
public class Calculator extends JFrame implements ActionListener
{
int m=0,i,n=0,a=0,point=0;
float sum=0,s1,s2,equ;
String v="";
JPanel delete_main = new JPanel();
JPanel delete = new JPanel();
计算器Java编程完全代码
计算器Java编程代码1、界面截图1、程序代码import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Counter implements ActionListener {// 改进小数问题private boolean append = false;JButton[] jb = new JButton[20];JTextField jtf = new JTextField(19);String[] st = { "Backs", "CE", "C", "+", " 7 ", " 8 ", " 9", "-"," 4 ", " 5 ", " 6", "*", " 1 ", " 2 ", " 3", "/"," . ", "+/-", " 0", "=", };String num1 = "0";String operator = "+";public Counter() {JFrame jf = new JFrame("计算器");// 界面设置GridLayout gl = new GridLayout(6, 1);jf.setLayout(gl);JPanel jp0 = new JPanel();jp0.add(jtf);jf.add(jp0);JPanel jp1 = new JPanel();for (int i = 0; i < 4; i++) {jb[i] = new JButton(st[i]);jp1.add(jb[i]);}jf.add(jp1);JPanel jp2 = new JPanel();for (int i = 4; i < 8; i++) {jb[i] = new JButton(st[i]);jp2.add(jb[i]);}jf.add(jp2);JPanel jp3 = new JPanel();for (int i = 8; i < 12; i++) {jb[i] = new JButton(st[i]);jp3.add(jb[i]);}jf.add(jp3);JPanel jp4 = new JPanel();for (int i = 12; i < 16; i++) { jb[i] = new JButton(st[i]);jp4.add(jb[i]);}jf.add(jp4);JPanel jp5 = new JPanel();for (int i = 16; i < 20; i++) { jb[i] = new JButton(st[i]);jp5.add(jb[i]);}jf.add(jp5);jtf.setEditable(false);// 文本框不可编辑jf.setResizable(false);// 窗口不可编辑jf.pack();// 自动调整窗口的大小// jf.setSize(240, 220);jf.setLocation(450, 300);jf.setVisible(true);jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);for (int i = 0; i < 20; i++) {// 注册监听jb[i].addActionListener(this);}}public void actionPerformed(ActionEvent ae) {String s = ae.getActionCommand();if (s.trim().matches("^\\d$")) {// 判断是输入的是否是数字if (append) {// 追加数字String ss = jtf.getText().trim();jtf.setText(ss + s.trim());} else {// 替换文本框原来的数字jtf.setText(s.trim());append = true;}} else if ("+-/*".indexOf(s.trim()) != -1) {// 判断按的是否是四则运算符num1 = jtf.getText();// 将第一次输入的数存储起来operator = s.trim();// 将输入的符号存储起来append = false;} else if ("=".equals(s.trim())) {String num2 = jtf.getText();double d1 = Double.parseDouble(num1);double d2 = Double.parseDouble(num2);if ("+".equals(operator)) {// 加法运算d1 = d1 + d2;} else if ("-".equals(operator)) {// 减法运算d1 = d1 - d2;} else if ("*".equals(operator)) {// 乘法运算d1 = d1 * d2;} else if ("/".equals(operator)) {// 除法运算d1 = d1 / d2;}jtf.setText(d1 + "");// 显示结果append = false;} else if (".".equals(s.trim())) {// 判断小数点String temp = jtf.getText();if (temp.indexOf(".") == -1) {jtf.setText(temp + ".");append = true;}} else if ("+/-".equals(s.trim())) {// 判断+/-String temp = jtf.getText();if(temp.startsWith("-")) {// 如果该数是负数则取负号后的数字jtf.setText(temp.substring(1));} else {// 如果是正数则在这个数前加上负号jtf.setText("-" + temp);}} else if ("CE".equals(s.trim()) || "C".equals(s.trim())) {// 判断复位键jtf.setText("0");append = false;} else if ("BackS".equals(s.trim())) {// 判断BackS键(删除)String temp = jtf.getText();if (temp.length() > 0) {jtf.setText(temp.substring(0, temp.length() - 1));}}}public static void main(String[] args) {new Counter();}}。
用java代码写的简易计算器(可以实现基本的加减乘除功能)
⽤java代码写的简易计算器(可以实现基本的加减乘除功能)package A;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.*;public class Calcular3 extends JFrame implements ActionListener,MouseListener{private int m1=0,n=0;//private double m2=0;//运算的数private int flag=0;JFrame f;JPanel p1,p2,p3;JTextField t;JButton b1[]=new JButton[18];String b[]= {"1","2","3","4","5","6","7","8","9","0","清空","退格",".","=","+","-","*","/"};public Calcular3(){f=new JFrame("计算器");t=new JTextField(35);p1=new JPanel();p2=new JPanel();p3=new JPanel();f.setBounds(100, 100, 400, 200);f.add(p1,BorderLayout.NORTH);f.add(p2,BorderLayout.CENTER);f.add(p3,BorderLayout.EAST);p2.setLayout(new GridLayout(5,3));p3.setLayout(new GridLayout(4,1));p1.add(t);for(int i=0;i<14;i++) {b1[i]=new JButton(b[i]);p2.add(b1[i]);b1[i].addActionListener(this);}for(int i=14;i<18;i++) {b1[i]=new JButton(b[i]);p3.add(b1[i]);b1[i].addActionListener(this);}/*for(int i=0;i<18;i++) {b1[i].addActionListener(this);}*/f.setVisible(true);}//实现接⼝的⽅法public void mouseClicked(MouseEvent e) {}public void mousePressed(MouseEvent e) {}public void mouseReleased(MouseEvent e) {}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void actionPerformed(ActionEvent e) {String str="";int i;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {if(i==9) {n=n*10;}else {n=n*10+i+1;}str=String.valueOf(n);//整形n转换成字符串strt.setText(str);//显⽰到⽂本框上}}for(i=14;i<18;i++) {//+、-、*、/if(e.getSource()==b1[i]) {//匹配运算符m1=Integer.parseInt(t.getText());if(flag==15) {m2=m1+m2;}else if(flag==16) {m2=m1-m2;}else if(flag==17) {m2=m1*m2;}else if(flag==18) {m2=m1/m2;}else m2=m1;//若⽆连续的运算符运算,保存当前数据到m2 if(i==14) flag=15;else if(i==15) flag=16;else if(i==16) flag=17;else flag=18;str=String.valueOf(b[i]);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据break;//找到匹配数据退出循环}}if(e.getSource()==b1[13]) {//=m1=Integer.parseInt(t.getText());if(flag==15) {m2=m2+m1;}else if(flag==16) {m2=m2-m1;}else if(flag==17) {m2=m2*m1;}else if(flag==18) {m2=m2/m1;}else m2=m1;str=String.valueOf(m2);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据flag=0;//flag还原0,表明没有未处理的运算符}if(e.getSource()==b1[10]) {//各变量变为0 清空m1=0;m2=0;flag=0;n=0;t.setText("0");//显⽰到⽂本框上}if(e.getSource()==b1[11]) {//退格m1=(int)(Double.parseDouble(t.getText())/10);n=m1;str=String.valueOf(m1);t.setText(str);}if(e.getSource()==b1[12]) {//⼩数点m1=Integer.parseInt(t.getText());str=String.valueOf(m1+b[12]);t.setText(str);//显⽰到⽂本框上int j=0;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {j++;m2=Math.pow(0.1, j)*Integer.parseInt(b[i]);str=String.valueOf(m1+m2);t.setText(str);//显⽰到⽂本框上}}}}//主函数public static void main(String[] args) {new Calcular3();}}。
java计算器程序代码
import java.awt.*;//计算器实例import java.awt.event.*;public class calculator{public static void main(String args[]){MyWindow my=new MyWindow("计算器");}}class MyWindow extends Frame implements ActionListener{ StringBuffer m=new StringBuffer();int p;TextField tex;Buttonb0,b1,b2,b3,b4,b5,b6,b7,b8,b9,jia,jian,cheng,chu,deng,dian,qingling,kaifang;MyWindow(String s){super(s);//StringBuffer s2=new StringBuffer();//String s;tex=new TextField(18);b0=new Button(" 0 ");b1=new Button(" 1 ");b2=new Button(" 2 ");b3=new Button(" 3 ");b4=new Button(" 4 ");b5=new Button(" 5 ");b6=new Button(" 6 ");b7=new Button(" 7 ");b8=new Button(" 8 ");b9=new Button(" 9 ");dian=new Button(" . ");jia=new Button(" + ");jian=new Button(" - ");cheng=new Button(" × ");chu=new Button(" / ");deng=new Button(" = ");qingling=new Button(" 清零 ");kaifang=new Button(" √ ");setLayout(new FlowLayout());add(tex);add(b0);add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);add(b9);add(dian);add(jia);add(jian);add(cheng);add(chu);add(kaifang);add(qingling);add(deng);b0.addActionListener(this);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);b5.addActionListener(this);b6.addActionListener(this);b7.addActionListener(this);b8.addActionListener(this);b9.addActionListener(this);jia.addActionListener(this);jian.addActionListener(this);cheng.addActionListener(this);chu.addActionListener(this);dian.addActionListener(this);deng.addActionListener(this);qingling.addActionListener(this); kaifang.addActionListener(this);setBounds(200,200,160,280);setResizable(false);//不可改变大小setVisible(true);validate();addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent ee){ System.exit(0);}});}public void actionPerformed(ActionEvent e){if(e.getSource()==b0){m=m.append("0");tex.setText(String.valueOf(m));}if(e.getSource()==b1){m=m.append("1"); tex.setText(String.valueOf(m)); }if(e.getSource()==b2){m=m.append("2"); tex.setText(String.valueOf(m)); }if(e.getSource()==b3){m=m.append("3"); tex.setText(String.valueOf(m)); }if(e.getSource()==b4){m=m.append("4"); tex.setText(String.valueOf(m));}if(e.getSource()==b5){m=m.append("5"); tex.setText(String.valueOf(m)); }if(e.getSource()==b6){m=m.append("6"); tex.setText(String.valueOf(m)); }if(e.getSource()==b7){m=m.append("7"); tex.setText(String.valueOf(m)); }if(e.getSource()==b8){m=m.append("8"); tex.setText(String.valueOf(m)); }if(e.getSource()==b9){m=m.append("9"); tex.setText(String.valueOf(m)); }if(e.getSource()==jia){m=m.append("+"); tex.setText(String.valueOf(m)); }if(e.getSource()==jian){m=m.append("-"); tex.setText(String.valueOf(m)); }if(e.getSource()==cheng){m=m.append("*"); tex.setText(String.valueOf(m)); }if(e.getSource()==chu){m=m.append("/"); tex.setText(String.valueOf(m)); }if(e.getSource()==dian){m=m.append("."); tex.setText(String.valueOf(m)); }String mm=String.valueOf(m);int p1=mm.indexOf("+");int p2=mm.indexOf("-");int p3=mm.indexOf("*");int p4=mm.indexOf("/");if(p1!=-1){p=p1;}else if(p3!=-1){p=p3;}else if(p2!=-1){p=p2;}else if(p4!=-1){p=p4;}if(e.getSource()==deng){String m1=mm.substring(0,p);String m2=mm.substring(p+1);String ch=mm.substring(p,p+1);//System.out.println(m1);//System.out.println(m2);//System.out.println(ch);if(ch.equals("+")){float n1=Float.parseFloat(m1); float n2=Float.parseFloat(m2); float sum=n1+n2;String su=String.valueOf(sum); tex.setText(su);}if(ch.equals("-")){float n1=Float.parseFloat(m1);float n2=Float.parseFloat(m2);float sum=n1-n2;String su=String.valueOf(sum);tex.setText(su);}if(ch.equals("*")){float n1=Float.parseFloat(m1);float n2=Float.parseFloat(m2);float sum=n1*n2;String su=String.valueOf(sum);tex.setText(su);}if(ch.equals("/")){float n1=Float.parseFloat(m1);float n2=Float.parseFloat(m2);float sum=n1/n2;String su=String.valueOf(sum);tex.setText(su);}}if(e.getSource()==qingling){StringBuffer kk=new StringBuffer(); m=kk;tex.setText("0");// System.out.println(mm);}if(e.getSource()==kaifang){String t=tex.getText();float num=Float.parseFloat(t);double nub=Math.sqrt(num);tex.setText(String.valueOf(nub)); }}}。
计算器完整代码(java)
1. Calculator 类import java.applet.*;import java.awt.*;import java.awt.event.*;import ng.*;import java.applet.Applet;import javax.swing.*;import javax.swing.border.*;public class Calculator extends JApplet implements ActionListener {private final String[] KEYS={"7","8","9","/","sqrt", "4","5","6","*","%","1","2","3","-","1/x","0","+/-",".","+","="};private final String[] COMMAND={"Backspace","CE","C"};private final String[] M={" ","MC","MR","MS","M+"};private JButton keys[]=new JButton[KEYS.length];private JButton commands[]=new JButton[COMMAND.length];private JButton m[]=new JButton[M.length];private JTextField display =new JTextField("0");// public JTextField setHorizontalAlignment(int alignment);// private JTextFielddisplay.setHorizontalAlignment(JTextField.RIGHT)=new JTextField("0"); private void setup(){display.setHorizontalAlignment(JTextField.RIGHT);JPanel calckeys=new JPanel();JPanel command=new JPanel();JPanel calms=new JPanel();calckeys.setLayout(new GridLayout(4,5,3,3));command.setLayout(new GridLayout(1,3,3,3));calms.setLayout(new GridLayout(5,1,3,3));for(int i=0;i<KEYS.length;i++){keys[i]=new JButton(KEYS[i]);calckeys.add(keys[i]);keys[i].setForeground(Color.blue);}keys[3].setForeground(Color.red);keys[4].setForeground(Color.red);keys[8].setForeground(Color.red);keys[9].setForeground(Color.red);keys[13].setForeground(Color.red);keys[14].setForeground(Color.red);keys[18].setForeground(Color.red);keys[19].setForeground(Color.red);for(int i=0;i<COMMAND.length;i++){commands[i]=new JButton(COMMAND[i]);command.add(commands[i]);commands[i].setForeground(Color.red);}for(int i=0;i<M.length;i++){m[i]=new JButton(M[i]);calms.add(m[i]);m[i].setForeground(Color.red);}JPanel panel1=new JPanel();panel1.setLayout(new BorderLayout(3,3));panel1.add("North",command);panel1.add("Center",calckeys);JPanel top=new JPanel();top.setLayout(new BorderLayout());display.setBackground(Color.WHITE);top.add("Center",display);getContentPane().setLayout(new BorderLayout(3,5)); getContentPane().add("North",top);getContentPane().add("Center",panel1); getContentPane().add("West",calms);}public void init(){setup();for(int i=0;i<KEYS.length;i++){keys[i].addActionListener(this);}for(int i=0;i<COMMAND.length;i++){commands[i].addActionListener(this);}for(int i=0;i<M.length;i++){m[i].addActionListener(this);}display.setEditable(false);}public void actionPerformed(ActionEvent e){String label=e.getActionCommand();// double zero=e.getActionCommand();if(label=="C")handleC();else if(label=="Backspace")handleBackspace();else if(label=="CE")display.setText("0");else if (label=="1/x")daoShu();else if(label=="sqrt"){display.setText(Math.sqrt(getNumberFromDisplay())+"");}else if("0123456789.".indexOf(label)>=0){handleNumber(label);// handlezero(zero);}elsehandleOperator(label);}private boolean firstDigit=true;private void handleNumber(String key){if(firstDigit){ if(key.equals("0"))display.setText(key);else if(key.equals(".")){display.setText("0.");firstDigit=false;}else if(!key.equals("0")&&!key.equals(".")){display.setText(key);firstDigit=false;}}else if((key.equals("."))&&(display.getText().indexOf(".")<0)) display.setText(display.getText()+".");else if(!key.equals(".")&&display.getText().length()<=32) display.setText(display.getText()+key);}private double number=0;private String operator="=";private void handleOperator(String key){if(operator.equals("/")){if(getNumberFromDisplay()==0){display.setText("除数不能为零");}else{number/=getNumberFromDisplay();}long t1;double t2;t1=(long)number;t2=number-t1;if(t2==0){display.setText(String.valueOf(t1));}else{display.setText(String.valueOf(number));}}else if(operator.equals("+"))number+=getNumberFromDisplay();else if(operator.equals("-"))number-=getNumberFromDisplay();else if(operator.equals("*"))number*=getNumberFromDisplay();else if(operator.equals("%"))number=number/100;else if(operator.equals("+/-"))number=number*(-1);else if(operator.equals("="))number=getNumberFromDisplay();long t1;double t2;t1=(long)number;t2=number-t1;if(t2==0)display.setText(String.valueOf(t1));elsedisplay.setText(String.valueOf(number));operator=key;firstDigit=true;}private double getNumberFromDisplay(){return Double.valueOf(display.getText()).doubleValue(); }private void handleC(){display.setText("0");firstDigit=true;operator="=";}private void handleBackspace(){String text=display.getText();int i=text.length();if(i>0){text=text.substring(0,i-1);if(text.length()==0){display.setText("0");firstDigit=true;operator="=";}elsedisplay.setText(text);}}private void daoShu(){if (display.getText().equals("0")){display.setText("除数不能为零");System.out.println(1);}else{long l;double d=1/getNumberFromDisplay();l=(long)d;System.out.println(d);System.out.println(l);display.setText(String.valueOf(d));}}}2.CalFrame 类import java.awt.Color;importimport java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.JApplet;import javax.swing.JFrame;public class Test {public static void main(String[] args) {JFrame f=new JFrame();f.getAccessibleContext();Calculator Calculator1=new Calculator(); Calculator1.init();f.getContentPane().add("Center",Calculator1);f.setVisible(true);f.setBounds(300, 200,380,245);f.setBackground(Color.LIGHT_GRAY);f.validate();f.setResizable(false);f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});f.setTitle("计算器");}}。
JAVA简易计算器程序源代码
JAVA简易计算器程序源代码package myText;import java.awt.*;import javax.swing.*;import java.awt.event.*;import javax.swing.border.*;public class Calculator extends JFrame implements ActionListener{ private JPanel Panel1=new JPanel();private JPanel Panel2=new JPanel();private JTextField tfResult=new JTextField(25);private JLabel label=new JLabel("计算结果:");private String recentOperation=null;private String recentNum=null;private boolean isNew=true;public void addButton(Container c,String s){JButton b=new JButton(s);b.setFont(new java.awt.Font("SansSerif",0,12));b.setForeground(Color.red);b.setBorder(BorderFactory.createRaisedBevelBorder());c.add(b);b.addActionListener(this);}//end public void addButton(Container c,String s)public void actionPerformed(ActionEvent e){String s=e.getActionCommand();if(s.charAt(0)>='0'&&s.charAt(0)<='9'){if(!isNew){tfResult.setText(tfResult.getText()+s);}//end if(!isNew)else{tfResult.setText(s);}//end elseisNew=false;}//end if(s.charAt(0)>='0'&&s.charAt(0)<='9') else if(s.equals(".")){if(tfResult.getText().indexOf(".")!=-1)return;if(!isNew&&tfResult.getText()!=""){tfResult.setText(tfResult.getText()+".");}//end ifelse{tfResult.setText("0.");}//end elseisNew=false;}//end if(s.equals("."))else if(s.equals("=")){equalaction(e);}//end if(s.equals("="))else{if((tfResult.getText()).equals("")){return;}//endif((tfResult.getText()).equals(""))if(recentOperation!=null){equalaction(e);}//end if(recentOperation!=null) recentOperation=s;recentNum=tfResult.getText();isNew=true;}//end else}//end public void actionPerformed(ActionEvent e) void equalaction(ActionEvent e){if(recentOperation==null||recentNum==null||tfResult.getTex t().equals("")){ return;}//end if()double last=0,now=0;try{last=Double.parseDouble(recentNum);now=Double.parseDouble(tfResult.getText());}//end trycatch(NumberFormatException ne){recentOperation=null;recentNum=null;tfResult.setText("数据输入不合法");System.out.println("数据输入不合法");isNew=true;return;}//end catch(NumberFormatException ne)if(recentOperation.equals("+")){last+=now;}//end if(recentOperation.equals("+"))if(recentOperation.equals("-")){last-=now;}//endif(recentOperation.equals("-"))if(recentOperation.equals("*")){last*=now;}//endif(recentOperation.equals("*"))if(recentOperation.equals("/")){last/=now;}//endif(recentOperation.equals("/"))tfResult.setText(""+last);recentNum=tfResult.getText();recentOperation=null;isNew=true;}//end void equalaction(ActionEvent e)public Calculator(){tfResult.setBorder(BorderFactory.createLoweredBevelBorder ());tfResult.setEditable(false);tfResult.setText("0");tfResult.setHorizontalAlignment(SwingConstants.RIGHT);////本java源代码由839682048整理修改//////Panel1.add(label,FlowLayout.LEFT);Panel1.add(tfResult);////本java源代码由839682048整理修改///Panel2.setLayout(new GridLayout(4,4,2,2));String buttons="789/456*123-0.=+";for(int i=0;i<buttons.length();i++){< p="">addButton(Panel2,buttons.substring(i,i+1));}//end for()//本java源代码由839682048整理修改///this.getContentPane().add(Panel1,"North");this.getContentPane().add(Panel2,"Center");this.setResizable(false);this.setTitle("计算器");this.addWindowListener(newjava.awt.event.WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}//end public Calculator1()public static void main(String[]args){Calculator mf=new Calculator();mf.setBounds(200,200,400,400);mf.show();}//end main()}//end public class Calculator1extends JFrame implements ActionListener</buttons.length();i++){<>。
JAVA编写的计算器源代码
JAVA编写的计算器源代码// Calculator.javaimport javax.swing.*; // 引入swing库import java.awt.*; // 引入awt库import java.awt.event.*; // 引入awt.event库public class Calculator extends JFrame implements ActionListener//定义按钮private JButton zero;private JButton one;private JButton two;private JButton three;private JButton four;private JButton five;private JButton six;private JButton seven;private JButton eight;private JButton nine;private JButton point;private JButton equal; private JButton plus; private JButton minus; private JButton multiply; private JButton divide; private JButton backspace; private JButton ac;private JButton ce;private JButton sqrt; private JButton sqr;private JButton plus_minus; private JButton delete; private JButton sin;private JButton cos;private JButton tan;private JButton log;private JButton nfactorial; private JButton cubic; private JButton coln;private JButton factorial;//定义文本框private JTextField resulttext;// 定义boolean变量boolean clrdisp = true; // 昵称确定是否清除计算器显示boolean isCalculate = false; // 是否可以执行计算// 定义String变量,用于存储操作符String optr;//定义存储第一个操作数double num1;//初始化构造函数public Calculato//设置布局setLayout(new BorderLayout();//创建面板JPanel northPanel = new JPanel(;JPanel centerPanel = new JPanel(;JPanel southPanel = new JPanel(;//设置面板布局northPanel.setLayout(new FlowLayout(); centerPanel.setLayout(new GridLayout(4, 5)); southPanel.setLayout(new FlowLayout();//设置计算器显示resulttext = new JTextField(28); northPanel.add(resulttext);resulttext.setEditable(false);//初始化按钮zero = new JButton("0");one = new JButton("1");two = new JButton("2");three = new JButton("3");four = new JButton("4");five = new JButton("5");six = new JButton("6");seven = new JButton("7");eight = new JButton("8");nine = new JButton("9");point = new JButton(".");equal = new JButton("=");plus = new JButton("+");minus = new JButton("-"); multiply = new JButton("*"); divide = new JButton("/"); backspace = new JButton("<-"); ac = new JButton("AC");ce = new JButton("CE");sqrt = new JButton("sqrt");sqr = new JButton("sqr");plus_minus = new JButton("+/-");。
超级简单明了的JAVA计算器代码
package caculator;import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;public class caculator extends JFrame implements ActionListener { double sum=0;static double getValue;static int action ;int i=0,j=0,p=0,l;double par1;JButton Jk=new JButton("k");JButton J1 = new JButton("1");JButton J2 = new JButton("2");JButton J3 = new JButton("3");JButton J4 = new JButton("4");JButton J5 = new JButton("5");JButton J6 = new JButton("6");JButton J7 = new JButton("7");JButton J8 = new JButton("8");JButton J9 = new JButton("9");JButton J0 = new JButton("0");JButton Je = new JButton("=");JButton Ja = new JButton("+");JButton Jr = new JButton("-");JButton Jm = new JButton("*");JButton Jd = new JButton("/");JButton Jc = new JButton("清除");JButton Jpt = new JButton(".");JTextArea show = new JTextArea("");caculator(){super("caculator");setLocation(200,200);setSize(300,350);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);JPanel jp = new JPanel();jp.setLayout(null);jp.add(J1);jp.add(J2);jp.add(J3);jp.add(J4);jp.add(J5);jp.add(J6);jp.add(J7);jp.add(J8);jp.add(J9);jp.add(J0);jp.add(Je);jp.add(Ja);jp.add(Jr);jp.add(Jm);jp.add(Jd);jp.add(Jc);jp.add(Je);jp.add(Jpt);J9.setBackground(Color.pink); J8.setBackground(Color.pink); J7.setBackground(Color.pink); J6.setBackground(Color.pink); J5.setBackground(Color.pink); J4.setBackground(Color.pink); J3.setBackground(Color.pink); J2.setBackground(Color.pink); J1.setBackground(Color.pink); J0.setBackground(Color.pink);Je.setBackground(Color.pink);Ja.setBackground(Color.pink); Jr.setBackground(Color.pink); Jm.setBackground(Color.pink); Jd.setBackground(Color.pink); Jc.setBackground(Color.pink); Jpt.setBackground(Color.pink);J7.setBounds(10,70,60,50);J8.setBounds(75,70,60,50);J9.setBounds(140,70,60,50); J4.setBounds(10,125,60,50); J5.setBounds(75,125,60,50); J6.setBounds(140,125,60,50); J1.setBounds(10,180,60,50); J2.setBounds(75,180,60,50); J3.setBounds(140,180,60,50); J0.setBounds(10,235,60,50); Je.setBounds(75,235,60,50); Jpt.setBounds(140,235,60,50);Jd.setBounds(205,70,60,50); Jm.setBounds(205,125,60,50); Jr.setBounds(205,180,60,50); Ja.setBounds(205,235,60,50); Jc.setBounds(205,10,60,50);J1.addActionListener(this);J2.addActionListener(this);J3.addActionListener(this);J4.addActionListener(this);J5.addActionListener(this);J6.addActionListener(this);J7.addActionListener(this);J8.addActionListener(this);J9.addActionListener(this);J0.addActionListener(this);Ja.addActionListener(this);Jr.addActionListener(this);Jm.addActionListener(this);Je.addActionListener(this);Jc.addActionListener(this);Jpt.addActionListener(this);jp.add(show);show.setBackground(Color.pink);show.setBounds(10,10,180,50);setContentPane(jp);}@Overridepublic void actionPerformed(ActionEvent e) { if(e.getSource()==J0){show.setText("0"); }if(e.getSource()==J1){show.setText("1");}if(e.getSource()==J2){show.setText("2");}if(e.getSource()==J3){show.setText("3");}if(e.getSource()==J4){show.setText("4");}if(e.getSource()==J5){show.setText("5");}if(e.getSource()==J6){show.setText("6");}if(e.getSource()==J7){show.setText("7");}if(e.getSource()==J8){show.setText("8");}if(e.getSource()==J9){show.setText("9");}par1=Double.parseDouble(show.getText()); if(e.getSource()==Ja){show.setText("");if(j==0){sum=par1;}else if(action==1){sum+=par1;}setsum();j++;p=0;i=0;action = 1;} if(e.getSource()==Jr){show.setText("");if(j==0){sum=par1;}else if(action==2){sum-=par1;}setsum();j++;p=0;i=0;action = 2;}if(e.getSource()==Jm){show.setText(""); if(j==0){sum=par1;}else if(action==3){sum*=par1;}setsum();j++;p=0;i=0;action = 3;}if(e.getSource()==Jd){show.setText(""); if(j==0){sum=par1;}else if(action==4){sum/=par1;}setsum();j++;p=0;i=0;action = 4;if(e.getSource()==Jc){clear();}if(e.getSource()==Jpt){show.append(".");}if(e.getSource()==Je){switch(action){case 1:show.setText(String.valueOf(sum+=par1)); break;case 2:show.setText(String.valueOf(sum-=par1)); break;case 3:show.setText(String.valueOf(sum*=par1)); break;case 4:show.setText(String.valueOf(sum/=par1)); break;}i=0;j=0;action=0;}}private void setsum() {show.setText(String.valueOf(sum));String s=show.getText();}void clear(){i=0;j=0;p=0;sum=0;action=0;show.setText("0"); }// TODO Auto-generated method stubpublic static void main(String args[]){caculator ct=new caculator();}}。
计算器(JAVA)源代码
//定义计算的类import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JTextField;public class Caculate implements ActionListener { //设置属性private String data;private JTextField text;private String result = "0";private boolean start_new = false;private double last_value = 0;private String ope = "";private double value = 0;public String getResult (){return result;}//定义一个构造方法public Caculate(JTextField text){this.text = text;}@Override//按钮事件处理public void actionPerformed(ActionEvent cal) { // TODO Auto-generated method stubdata = cal.getActionCommand();data = data.trim();if("0123456789".indexOf(data) != -1){numButton(data);}else if (".".indexOf(data) != -1){dotButton(data);}else if ("+-*/".indexOf(data) != -1){operateButton(data);}else if ("=".indexOf(data)!=-1){equalButton();}//System.out.println(data);System.out.println(result);text.setText(result);}//计算程序private void numButton(String da){if(!start_new){result = result + da;}else{result = da;}while (result.startsWith("0")&&!result.startsWith("0.")&&result.length()>0){ result = result.substring(1);}start_new = false;}private void dotButton(String da){if(da.indexOf(".")!= -1){result = result + da;}}private void operateButton(String da){if(result.length()>0){last_value = Double.parseDouble(result);ope = da;start_new = true;}}private void equalButton(){value = Double.parseDouble(result);if(ope.equals("+")){result = String.valueOf(last_value + value);}else if(ope.equals("-")){result = String.valueOf(last_value - value);}else if(ope.equals("*")){result = String.valueOf(last_value * value);}else if(ope.equals("/")){if(value == 0){result = "ERROR";}else{result = String.valueOf(last_value / value);}}// 去掉结尾的“.0000...”if (result.matches(".+\\.0+")) {result = result.substring(0, stIndexOf("."));}// 设置状态start_new = true;ope = "";}}import javax.swing.JTextField;public class Culator {private static final String String = null;JTextField op;private String re;/*** @param args*/public static void main(String[] args) {Culator cul = new Culator();cul.init();// TODO Auto-generated method stub}public void init(){javax.swing.JFrame frame = new javax.swing.JFrame(); frame.setTitle("计算器");java.awt.FlowLayout f1= new java.awt.FlowLayout();frame.setLayout(f1);javax.swing.JMenuBar cai = createMB();frame.setJMenuBar(cai);javax.swing.JButton mc = new javax.swing.JButton("MC");op= new javax.swing.JTextField("0",25);//设置数字从右边开始显示op.setHorizontalAlignment(JTextField.RIGHT);//设置按钮javax.swing.JButton mr = new javax.swing.JButton("MR"); javax.swing.JButton ms = new javax.swing.JButton("MS"); javax.swing.JButton mp = new javax.swing.JButton("M+"); javax.swing.JButton mm = new javax.swing.JButton("M-"); javax.swing.JButton delete = new javax.swing.JButton(" ←"); javax.swing.JButton ce = new javax.swing.JButton("CE "); javax.swing.JButton c = new javax.swing.JButton(" C "); javax.swing.JButton pm = new javax.swing.JButton(" ± "); javax.swing.JButton r = new javax.swing.JButton(" √"); javax.swing.JButton seven = new javax.swing.JButton(" 7 "); javax.swing.JButton eight = new javax.swing.JButton(" 8 "); javax.swing.JButton nine = new javax.swing.JButton(" 9 ");javax.swing.JButton under = new javax.swing.JButton(" / ");javax.swing.JButton percent = new javax.swing.JButton(" % ");javax.swing.JButton four = new javax.swing.JButton(" 4 ");javax.swing.JButton five = new javax.swing.JButton(" 5 ");javax.swing.JButton six = new javax.swing.JButton(" 6 ");javax.swing.JButton and = new javax.swing.JButton(" * ");javax.swing.JButton ds = new javax.swing.JButton("1/x");javax.swing.JButton one = new javax.swing.JButton(" 1 ");javax.swing.JButton two = new javax.swing.JButton(" 2 ");javax.swing.JButton three = new javax.swing.JButton(" 3 ");javax.swing.JButton m = new javax.swing.JButton(" - ");javax.swing.JButton equal = new javax.swing.JButton(" = ");javax.swing.JButton zero = new javax.swing.JButton(" 0 ");javax.swing.JButton dot = new javax.swing.JButton(" . ");javax.swing.JButton plus = new javax.swing.JButton(" + ");//添加按钮frame.add(op);frame.add(mc);frame.add(mr);frame.add(ms);frame.add(mp);frame.add(mm);frame.add(delete);frame.add(ce);frame.add(c);frame.add(pm);frame.add(r);frame.add(seven);frame.add(eight);frame.add(nine);frame.add(under);frame.add(percent);frame.add(four);frame.add(five);frame.add(six);frame.add(and);frame.add(ds);frame.add(one);frame.add(two);frame.add(three);frame.add(m);frame.add(equal);frame.add(zero);frame.add(dot);frame.add(plus);frame.setSize(290,300);//实例化一个Caculate类Caculate cal = new Caculate(op);//增加监听op.addActionListener(cal);mc.addActionListener(cal);mr.addActionListener(cal);ms.addActionListener(cal);mp.addActionListener(cal);mm.addActionListener(cal);delete.addActionListener(cal);ce.addActionListener(cal);c.addActionListener(cal);pm.addActionListener(cal);r.addActionListener(cal);seven.addActionListener(cal);eight.addActionListener(cal);nine.addActionListener(cal);under.addActionListener(cal); percent.addActionListener(cal);four.addActionListener(cal);five.addActionListener(cal);six.addActionListener(cal);and.addActionListener(cal);ds.addActionListener(cal);one.addActionListener(cal);two.addActionListener(cal);three.addActionListener(cal);m.addActionListener(cal);equal.addActionListener(cal);zero.addActionListener(cal);dot.addActionListener(cal);plus.addActionListener(cal);frame.setDefaultCloseOperation(3); frame.setResizable(false);frame.setVisible(true);}//创建一个设置TextField窗口容的函数//public void setOp(String re){// op.setText(re);//}//创建一个常带有菜单的菜单条,就加到JFrame上显示private javax.swing.JMenuBar createMB(){//创建菜单条javax.swing.JMenuBar mb = new javax.swing.JMenuBar();//创建查看菜单javax.swing.JMenu view = new javax.swing.JMenu("查看(V)");//创建菜单项javax.swing.JMenuItem biaozhun = new javax.swing.JMenuItem("标准型"); javax.swing.JMenuItem kexue = new javax.swing.JMenuItem("科学型"); javax.swing.JMenuItem chengxu = new javax.swing.JMenuItem("程序员"); javax.swing.JMenuItem tongji = new javax.swing.JMenuItem("统计信息"); javax.swing.JMenuItem history = new javax.swing.JMenuItem("历史");//将菜单项添加到菜单上view.add(biaozhun);view.add(kexue);view.add(chengxu);view.add(tongji);view.add(history);//创建编辑菜单javax.swing.JMenu operation = new javax.swing.JMenu("编辑(O)");//创建菜单项javax.swing.JMenuItem copy = new javax.swing.JMenuItem("复制"); javax.swing.JMenuItem paste = new javax.swing.JMenuItem("黏贴"); javax.swing.JMenuItem hr = new javax.swing.JMenuItem("历史记录");//将菜单项添加到菜单上operation.add(copy);operation.add(paste);operation.add(hr);//创建帮助菜单javax.swing.JMenu help = new javax.swing.JMenu("帮助(H)");//创建帮助菜单项javax.swing.JMenuItem vh = new javax.swing.JMenuItem("查看帮助"); javax.swing.JMenuItem about = new javax.swing.JMenuItem("关于计算器"); //将菜单项添加到菜单上help.add(vh);help.add(about);//加上一个分隔条help.addSeparator();//将菜单添加到菜单条上mb.add(view);mb.add(operation);mb.add(help);return mb;} }。
java计算器代码
import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Calculator extends JFrame{private Container container;//框架private JTextField tf;//定义文本框private Panel panel;private String cmd;private double result;//运算结果private boolean start;//运算开始判断Calculator(){super("李正刚-java简易计算器计算器");container = getContentPane();container.setLayout(new BorderLayout());//添加文本框tf = new JTextField("0.0");container.add(tf,BorderLayout.NORTH);tf.setHorizontalAlignment(JTextField.RIGHT);tf.setEditable(false);//嵌套容器panel = new Panel();container.add(panel);start = true;result = 0;//最后运算等号cmd = "=";ActionListener insert = new InsertAction(); ActionListener command = new CommandAction();//调用创建Button方法addButton("1",insert);addButton("2",insert);addButton("3",insert);addButton("0",insert);addButton("*",command);addButton("Back",insert);addButton("4",insert);addButton("5",insert);addButton("6",insert);addButton("+",command);addButton("/",command);addButton("Clear",insert);addButton("7",insert);addButton("8",insert);addButton("9",insert);addButton("-",command);addButton(".",insert);addButton("=",command);setSize(400,200);}private void addButton(String str,ActionListener listener){//添加Button方法(操作类型、注册监听器)JButton button=new JButton(str);button.addActionListener(listener);panel.setLayout(new GridLayout(3,6));panel.add(button);}private class InsertAction implements ActionListener{//插入,insertpublic void actionPerformed(ActionEvent event){String input=event.getActionCommand();if (start){tf.setText("");start=false;}if(input.equals("Back")){String str=tf.getText();if(str.length()>0)tf.setText(str.substring(0,str.length()-1)); }else if(input.equals("Clear")){tf.setText("0");start=true;}elsetf.setText(tf.getText()+input);}}private class CommandAction implements ActionListener{//计算,commandpublic void actionPerformed(ActionEvent e){String command=e.getActionCommand();if(start){cmd=command;}else{calculate(Double.parseDouble(tf.getText()));cmd=command;start=true;}}}public void calculate(double x){//加减乘除运算if (cmd.equals("+")) result+=x;else if (cmd.equals("-")) result-=x;else if (cmd.equals("*")) result*=x;else if (cmd.equals("/")) result/=x;else if (cmd.equals("=")) result= x;tf.setText(""+ result);}public static void main(String []args){Calculator mycalculator=new Calculator();mycalculator.setLocation(300,300);mycalculator.setVisible(true);}}。
计算器的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 javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;public class CalculatorB implements ActionListener { private JFrame frame;private JTextField field;private JButton[] allButtons;private JButton clearButton;// 构造初始化成员变量public CalculatorB() {frame = new JFrame("Calculator v1.1");field = new JTextField(25);allButtons = new JButton[16];String str = "123+456-789*0.=/";for (int i = 0; i < 16; i++) {allButtons[i] = new JButton(str.substring(i, i + 1)); }clearButton = new JButton("CLEAR");// 调用界面的初始化方法init();// 调用设置文本框的字体和颜色方法setFontAndColor();addEventHandler();}public void addEventHandler() {for (int i = 0; i < allButtons.length; i++) { allButtons[i].addActionListener(this); clearButton.addActionListener(this);}}private String op = null;private String m = null;private String n = null;private boolean cls = false;private void setResult() {if (field.getText().equals("")) {m = null;n = null;} else if (m != null) {n = field.getText();if (op.equals("+")) {field.setText(Double.parseDouble(m) + Double.parseDouble(n) + "");} else if (op.equals("-")) {field.setText(Double.parseDouble(m) - Double.parseDouble(n) + "");} else if (op.equals("*")) {field.setText(Double.parseDouble(m) * Double.parseDouble(n) + "");} else if (op.equals("/")) {field.setText(Double.parseDouble(m) / Double.parseDouble(n) + "");}cls = true;m = null;n = null;}}public void actionPerformed(ActionEvent e) {String str = e.getActionCommand();// 得到被点的按钮名称if ("0123456789.".indexOf(str) != -1) {field.setText("");cls = false;}field.setText(field.getText() + str); } else if ("+-*/".indexOf(str) != -1) { if (field.getText().equals("")) {op = str;} else if (m == null) {m = field.getText();op = str;field.setText("");} else if (m != null) {setResult();m = field.getText();op = str;}} else if (str.equals("=")) { setResult();} else if (str.equals("CLEAR")) { field.setText("");m = null;n = null;}}public void init() {frame.setLayout(new BorderLayout());JPanel northPannel = new JPanel();JPanel centerPannel = new JPanel();JPanel southPannel = new JPanel(); northPannel.setLayout(new FlowLayout()); centerPannel.setLayout(new GridLayout(4, 4)); southPannel.setLayout(new FlowLayout()); northPannel.add(field);southPannel.add(clearButton);for (int i = 0; i < allButtons.length; i++) { centerPannel.add(allButtons[i]);}frame.add(northPannel, BorderLayout.NORTH); frame.add(southPannel, BorderLayout.SOUTH); frame.add(centerPannel, BorderLayout.CENTER);}public void setFontAndColor() {field.setFont(new Font("宋体", Font.BOLD, 20)); field.setForeground(Color.PINK);field.setBackground(new Color(0x2a, 0x3b, 0x4f)); }public void showMe() {frame.pack(); // 系统调整大小---很重要// frame.setSize(600, 400);// 自定义窗体大小frame.setLocation(500, 400);// 设置窗体的启动位置frame.setResizable(false);frame.setVisible(true);frame.setDefaultCloseOperation(3);}public static void main(String[] args) {new CalculatorB().showMe();}}When you are old and grey and full of sleep, And nodding by the fire, take down this book, And slowly read, and dream of the soft look Your eyes had once, and of their shadows deep; How many loved your moments of glad grace, And loved your beauty with love false or true, But one man loved the pilgrim soul in you,And loved the sorrows of your changing face; And bending down beside the glowing bars, Murmur, a little sadly, how love fledAnd paced upon the mountains overheadAnd hid his face amid a crowd of stars.The furthest distance in the worldIs not between life and deathBut when I stand in front of youYet you don't know thatI love you.The furthest distance in the worldIs not when I stand in front of youYet you can't see my loveBut when undoubtedly knowing the love from both Yet cannot be together.The furthest distance in the worldIs not being apart while being in loveBut when I plainly cannot resist the yearningYet pretending you have never been in my heart. The furthest distance in the worldIs not struggling against the tidesBut using one's indifferent heartTo dig an uncrossable riverFor the one who loves you.倚窗远眺,目光目光尽处必有一座山,那影影绰绰的黛绿色的影,是春天的颜色。
java代码写的简易计算器(可以实现基本的加减乘除功能)
java代码写的简易计算器(可以实现基本的加减乘除功能)计算器java写⼀个计算器,要求实现加减乘除功能,并且能够循环接收新的数据,通过⽤户交互实现。
import java.util.Scanner;/*** 计算器* 写4个⽅法:加减乘除* 利⽤循环加switch进⾏⽤户交互* 传递需要操作的两个数* 输出结果*/public class Demo04 {public static double a;public static double b;//运算符public static String operator;//=符public static String equal;//结果public static double sum=0;public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("输⼊数字:");a = scanner.nextDouble();System.out.println("输⼊运算符:");operator = scanner.next();System.out.println("输⼊数字:");b = scanner.nextDouble();do {switch (operator){case "+":sum= add(a, b);System.out.println("输⼊=获取结果:");equal = scanner.next();coninue();break;case "-":sum=subtract(a,b);System.out.println("输⼊=获取结果:");equal = scanner.next();coninue();break;case "*":sum=multiply(a,b);System.out.println("输⼊=获取结果:");equal = scanner.next();coninue();break;case "/":if (b==0){System.out.println("被除数不能为0");operator = "q";break;}else {sum=divide(a,b);System.out.println("输⼊=获取结果:");equal = scanner.next();coninue();break;}default:System.out.println("运算符输⼊错误!");}}while (operator.equals("+")||operator.equals("-")||operator.equals("*")||operator.equals("/"));scanner.close();}//加public static double add(double a,double b){return a+b;}//减public static double subtract(double a,double b){return a-b;}//乘public static double multiply(double a,double b){return a*b;}//除public static double divide(double a,double b){return a/b;}//获得结果或再次输⼊public static void coninue(){Scanner scanner = new Scanner(System.in);if (equal.equals("=")){System.out.println(a+operator+b+"="+sum);System.out.println("输⼊运算符+,-,*,/继续或输⼊其他字符结束");operator=scanner.next();if (operator.equals("+")||operator.equals("-")||operator.equals("*")||operator.equals("/")){ System.out.println("输⼊数字:");b = scanner.nextDouble();a=sum;}else {System.out.println("输⼊错误!");}}else {System.out.println("输⼊错误!");}}}。
java简易计算器完整代码
java简易计算器完整代码import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;public class Calculate extends JFrame implements ActionListener {/****/private static final long serialVersionUID = 1L;/*** @param args*/float userFloata=0f;float userFloatb=0f;double result;JLabel label1 ;JLabel label2;JLabel label3;JTextField textField1;JTextField textField2;JTextField textField3;JButton addButton;JButton subtractButton;JButton rideButton;JButton divideButton;public Calculate(){setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setTitle("简易计算器");JPanel viewJPanel_1=new JPanel();JPanel viewJPanel_2=new JPanel();addButton=new JButton("加");addButton.addActionListener(this);viewJPanel_1.add(addButton);subtractButton=new JButton("减");subtractButton.addActionListener(this);viewJPanel_1.add(subtractButton);rideButton=new JButton("乘");rideButton.addActionListener(this);viewJPanel_1.add(rideButton);divideButton=new JButton("除");divideButton.addActionListener(this);viewJPanel_1.add(divideButton);label1=new JLabel("数据1:");viewJPanel_2.add(label1);textField1=new JTextField(5);textField1.addActionListener(this);viewJPanel_2.add(textField1);label2=new JLabel("数据2:");viewJPanel_2.add(label2);textField2=new JTextField(5);textField2.addActionListener(this);viewJPanel_2.add(textField2);label3=new JLabel("结果是:");viewJPanel_2.add(label3 );textField3=new JTextField(5);viewJPanel_2.add(textField3);setSize(420,120);setVisible(true);validate();getContentPane().add(viewJPanel_1,BorderLayout.NORTH);getContentPane().add(viewJPanel_2,BorderLayout.CENTER);}public void CalculateEventHandel(){try{userFloata= Float.parseFloat(textField1.getText().trim());userFloatb= Float.parseFloat(textField2.getText().trim());} catch (NumberFormatException e) {JOptionPane.showMessageDialog(this, "请输入数字型数据!");textField1.setText("");textField1.requestFocus();textField2.setText("");textField3.setText("");return;}}public static void main(String[] args) { // TODO Auto-generated method stubnew Calculate();//a.CalculateEventHandel();}public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stubif(e.getSource()==addButton){this.CalculateEventHandel();result=userFloata+userFloatb;// System.out.println(""+result);textField3.setText(""+result);}else if(e.getSource()==subtractButton){ this.CalculateEventHandel();result=userFloata-userFloatb;textField3.setText(""+result);}else if(e.getSource()==rideButton){this.CalculateEventHandel();result=userFloata*userFloatb;textField3.setText(""+result);}else if(e.getSource()==divideButton){this.CalculateEventHandel();result=userFloata/userFloatb;textField3.setText(""+result);}}}。
java简单计算器代码
java简单计算器代码Java简单计算器代码:```javaimport java.util.Scanner;public class Calculator {public static void main(String[] args) {Scanner input = new Scanner(System.in);double num1, num2, result = 0;char operator;System.out.print("请输入第一个数:");num1 = input.nextDouble();System.out.print("请输入运算符号(+、-、*、/):"); operator = input.next().charAt(0);System.out.print("请输入第二个数:");num2 = input.nextDouble();switch(operator) {case '+':result = num1 + num2;break;case '-':result = num1 - num2;break;case '*':result = num1 * num2;break;case '/':result = num1 / num2;break;default:System.out.println("运算符输入错误,请重新输入!");return;}System.out.println("运算结果:" + num1 + operator + num2 + "=" + result);}}```列表:1. 首先,在程序中导入`java.util.Scanner`包,以便从控制台读取用户输入内容。
java简易计算机代码
java简易计算机代码Java是一种面向对象的编程语言,广泛应用于计算机编程领域。
下面我们来看一段简易的Java代码,实现一个计算器的功能。
我们需要定义一个Calculator类,代码如下:```javapublic class Calculator {// 定义两个整型变量,用于存储输入的数字private int num1;private int num2;// 构造方法,用于初始化Calculator对象public Calculator(int num1, int num2) {this.num1 = num1;this.num2 = num2;}// 加法运算方法public int add() {return num1 + num2;}// 减法运算方法public int subtract() {return num1 - num2;}// 乘法运算方法public int multiply() {return num1 * num2;}// 除法运算方法public double divide() {// 判断除数是否为0,避免除以0的错误if (num2 != 0) {return (double)num1 / num2;} else {System.out.println("除数不能为0!");return 0;}}// 主方法,程序入口public static void main(String[] args) {// 创建一个Calculator对象,传入两个待计算的数值Calculator calculator = new Calculator(10, 5);// 调用加法运算方法,并输出结果int sum = calculator.add();System.out.println("两数之和:" + sum);// 调用减法运算方法,并输出结果int difference = calculator.subtract();System.out.println("两数之差:" + difference);// 调用乘法运算方法,并输出结果int product = calculator.multiply();System.out.println("两数之积:" + product);// 调用除法运算方法,并输出结果double quotient = calculator.divide();if (quotient != 0) {System.out.println("两数之商:" + quotient);}}}```在上面的代码中,我们首先定义了一个Calculator类,包含了两个私有的整型变量num1和num2,用于存储输入的数字。
java简单计算器代码
java简单计算器代码public class Calculator {public static void main(String[] args) {Calculator calculator = new Calculator(); //创建对象调⽤函数Scanner scanner = new Scanner(System.in); //创建scanner扫描对象,获取⽤户输⼊数据System.out.println("请输⼊第⼀个数据");double a=scanner.nextDouble();System.out.println("请输⼊运算符:");String operator=scanner.next();System.out.println("请输⼊第⼆个数据");double b= scanner.nextDouble();double result=0;//存储最后的计算结果scanner.close();//关闭scanner资源// 根据输⼊的运算符调⽤不同的⽅法if ("+".equals(operator)){//equals判断字符是否相等result= calculator.add(a,b);}//调⽤减法else if ("-".equals(operator)){result=calculator.sub(a,b);}else if ("*".equals(operator)){result=calculator.multiply(a,b);}else if ("/".equals(operator)){result=calculator.div(a,b);}System.out.println("最终结果为"+result);}public double add(double a,double b){return a+b;}public double sub(double a,double b){return a-b;}public double multiply(double a, double b){return a*b;}public double div(double a, double b){return a/b;}}。
java计算器代码
//计算器import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Calculator extends WindowAdapter implements ActionListener{JFrame frame;JTextField show;JButton bc,ce,c,ab,jia,jian,cheng,chu,equ,point,sqrt,zf,bfh,ds;//退格,复位,清空,关于,加,减,乘,除,等,点,2,加减,百分之,倒数JButton b[]=new JButton[10];//保存数字JDialog about;final int length=30;int i=0,j=0,action=0,p=0; //记录数字键连续时间次数double num=0,getValue;//记录计算结果的值,保存值public Calculator(){frame=new JFrame("计算器");frame.addWindowListener(this);frame.setSize(360, 230);frame.setLocation(380,260);frame.setLayout(new FlowLayout(FlowLayout.CENTER));frame.setResizable(false);show=new JTextField(31);show.setText("0");show.setHorizontalAlignment(SwingConstants.RIGHT);show.setEnabled(false);frame.add(show);Panel dispTop=new Panel();frame.add(dispTop);dispTop.setLayout(new GridLayout(1,4,3,3));bc=new JButton("BACK");bc.addActionListener(this);dispTop.add(bc);ce=new JButton("CE");ce.addActionListener(this);dispTop.add(ce);c=new JButton("C");c.addActionListener(this);dispTop.add(c);ab=new JButton("ABOUT");ab.addActionListener(this);dispTop.add(ab);//about弹出框about=new JDialog(frame,"关于计算器",true);about.addWindowListener(this);JLabel label=new JLabel("",JLabel.CENTER); about.add(label);about.setSize(200,100);about.setLocation(500,300);//数据显示区Panel dispMain=new Panel();frame.add(dispMain);dispMain.setLayout(new GridLayout(1,2,10,10));//按钮左面板Panel dispLeft=new Panel();frame.add(dispLeft);dispLeft.setLayout(new GridLayout(4,3,3,3));//四行三列//按钮右面板Panel dispRight=new Panel();frame.add(dispRight);dispRight.setLayout(new GridLayout(4,2,3,3));//四行两列for(int l=9;l>=0;l--){b[l]=new JButton(String.valueOf(l));dispLeft.add(b[l]);b[l].addActionListener(this);}zf=new JButton("+/-");zf.addActionListener(this);dispLeft.add(zf);point=new JButton(".");point.addActionListener(this);dispLeft.add(point);chu=new JButton("/");chu.addActionListener(this);dispRight.add(chu);sqrt=new JButton("sqrt");sqrt.addActionListener(this);dispRight.add(sqrt);cheng=new JButton("*");cheng.addActionListener(this);dispRight.add(cheng);bfh=new JButton("%");bfh.addActionListener(this);dispRight.add(bfh);jian=new JButton("-");jian.addActionListener(this);dispRight.add(jian);ds=new JButton("1/x");ds.addActionListener(this);dispRight.add(ds);jia=new JButton("+");jia.addActionListener(this);dispRight.add(jia);equ=new JButton("=");equ.addActionListener(this);dispRight.add(equ);frame.setVisible(true);}//计算器抽象会报错public void actionPerformed(ActionEvent e){getValue=Double.valueOf(show.getText()).doubleValue();for(int k=0;k<10;k++){if(e.getSource()==b[k]){if(i==0){show.setText("");}String str=show.getText();if(str.length()<length){show.setText(show.getText()+e.getActionCommand());}i++;}}if(e.getSource()==jia){if(j==0){num=getValue;}else if(action==1){num+=getValue;}show.setText(String.valueOf(num));j++;action=1;i=0;////}else if(e.getSource()==jian){if(j==0){num=getValue;}else if(action==2){num-=getValue;}show.setText(String.valueOf(num));j++;action=2;i=0;///}else if(e.getSource()==cheng){if(j==0){num=getValue;}else if(action==3){num*=getValue;}show.setText(String.valueOf(num));j++;action=3;i=0;////}else if(e.getSource()==chu){if(j==0){num=getValue;}else if(action==4){num/=getValue;}show.setText(String.valueOf(num));j++;action=4;i=0;////}else if(e.getSource()==equ){switch(action){case 1:show.setText(String.valueOf(num+getValue));break;case 2:show.setText(String.valueOf(num-getValue));break;case 3:show.setText(String.valueOf(num*getValue));break;case 4:show.setText(String.valueOf(num/getValue));break;}//show.setText(String.valueOf(num));j=0;action=0;p=0;i=0;}else if(e.getSource()==point){if(p==0){show.setText(show.getText()+e.getActionCommand());p=1;}}else if(e.getSource()==ce||e.getSource()==c){j=0;action=0;p=0;num=0;i=0;////show.setText("0");}else if(e.getSource()==bc){String str=show.getText();if(str.length()>1){show.setText("");for(int t=0;t<str.length()-1;t++){char c=str.charAt(t);show.setText(show.getText()+c);}}else{show.setText("0");}}else if(e.getSource()==ab){about.setVisible(true);}else if(e.getSource()==sqrt){num=Math.sqrt(getValue);show.setText(String.valueOf(num));j++;i=0;///}else if(e.getSource()==ds){num=1/getValue;show.setText(String.valueOf(num));j++;i=0;////}else if(e.getSource()==bfh){num=getValue/100;show.setText(String.valueOf(num));j++;i=0;}else if(e.getSource()==zf){String str=show.getText();char c=str.charAt(0);if(c=='-'){show.setText("");for(int t=1;t<str.length();t++){show.setText(show.getText()+str.charAt(t));}}else{if(getValue!=0){show.setText("-"+show.getText());}}i=0;}}//windows关闭时调用此方法public void windowClosing(WindowEvent e){ if(e.getSource()==about){about.setVisible(false);}else if(e.getSource()==frame){System.exit(0);}}public static void main(String[] args) {Calculator c1=new Calculator();}}。
java程序代码——计算器
import java.awt.event.ActionEvent;import java.awt.event.ActionListenerpublic class NewJFrame extends javax.swing.JFrame {public NewJFrame() {initComponents();}private void initComponents() {jPanel1 = new javax.swing.JPanel();jLabel1 = new javax.swing.JLabel();jLabel2 = new javax.swing.JLabel();jLabel3 = new javax.swing.JLabel();num1 = new javax.swing.JTextField();num2 = new javax.swing.JTextField();result = new javax.swing.JTextField();addBtn = new javax.swing.JButton();jMenuBar1 = new javax.swing.JMenuBar();jMenu1 = new javax.swing.JMenu();jMenu3 = new javax.swing.JMenu();jMenu2 = new javax.swing.JMenu();setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);jLabel1.setText("Num1:");jLabel2.setText("Num2:");jLabel3.setText("Num3:");addBtn.setText("Add");addBtn.addActionListener(new jisuanAC());javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);jPanel1.setLayout(jPanel1Layout);jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addGap(53, 53, 53).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alig nment.LEADING).addComponent(addBtn).addGroup(javax.swing.GroupLayout.Alignment.TRAILING,jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupL ayout.Alignment.TRAILING).addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup().addComponent(jLabel1).addGap(31, 31, 31).addComponent(num1,javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_V ALUE)).addGroup(jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout.createParallelGroup(javax.swin g.GroupLayout.Alignment.LEADING).addComponent(jLabel2).addComponent(jLabel3)).addPreferredGap(ponentPla cement.RELATED, 31, Short.MAX_V ALUE).addGroup(jPanel1Layout.createParallelGroup(javax.swin g.GroupLayout.Alignment.LEADING, false).addComponent(result).addComponent(num2,javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_V ALUE)))).addPreferredGap(ponentPlacement.R ELATED))).addGap(168, 168, 168)));jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addGap(19, 19, 19).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alig nment.BASELINE).addComponent(jLabel1).addComponent(num1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ponentPlacement.RELATED).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alig nment.BASELINE).addComponent(jLabel2).addComponent(num2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ponentPlacement.RELATED).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alig nment.BASELINE).addComponent(jLabel3).addComponent(result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(61, 61, 61).addComponent(addBtn).addContainerGap(81, Short.MAX_V ALUE)));jMenu1.setText("Operation");jMenu3.setText("Add");jMenu1.add(jMenu3);jMenuBar1.add(jMenu1);jMenu2.setText("Exit");jMenuBar1.add(jMenu2);setJMenuBar(jMenuBar1);javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());getContentPane().setLayout(layout);layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_V ALUE).addContainerGap()));layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_V ALUE).addContainerGap()));pack();}// </editor-fold>/*** @param args the command line arguments*/public static void main(String args[]) {java.awt.EventQueue.invokeLater(new Runnable() {public void run() {new NewJFrame().setVisible(true);}});}private class jisuanAC implements ActionListener{public void actionPerformed(ActionEvent e) {if(e.getSource()== addBtn){int number1 = Integer.parseInt(num1.getText());int number2 = Integer.parseInt(num2.getText());int rs = number1 + number2;result.setText(String.valueOf(rs));}}}// Variables declaration - do not modifyprivate javax.swing.JButton addBtn;private javax.swing.JLabel jLabel1;private javax.swing.JLabel jLabel2;private javax.swing.JLabel jLabel3;private javax.swing.JMenu jMenu1;private javax.swing.JMenu jMenu2;private javax.swing.JMenu jMenu3;private javax.swing.JMenuBar jMenuBar1;private javax.swing.JPanel jPanel1;private javax.swing.JTextField num1;private javax.swing.JTextField num2;private javax.swing.JTextField result;}。
java编写的计算器
package Calculator;import java.awt.*;import javax.swing.*;import ponent.*; import java.awt.TextComponent.*; import java.awt.event.*;//数字按钮class NumBtn extends JButton{int number;Insets insets=new Insets(1,1,1,1);public NumBtn(int i){super(""+i);number=i;setMargin(insets);}public int getNum(){return number;}}//运算按钮class OperBtn extends JButton{Insets insets=new Insets(1,1,1,1);String operator;public OperBtn(String str){super(str);operator=str;setMargin(insets);}public String getOper(){return operator;}}//记忆按钮class FunBtn extends JButton{Insets insets=new Insets(1,1,1,1);String function;public FunBtn(String str){super(str);function=str;setMargin(insets);}public String getFun(){return function;}}//数学按钮class MathBtn extends JButton{Insets insets=new Insets(1,1,1,1);String math;public MathBtn(String str){super(str);math=str;setMargin(insets);}public String getMath(){return math;}}public class Calculator extends JFrame implements ActionListener{Insets insets=new Insets(1,1,1,1);NumBtn numbtn[];OperBtn operbtn[];FunBtn funbtn[];MathBtn mathbtn[];String oper[]={"/","*","-","+"};String fun[]={"MC","MR","MS","M+"};String math[]={"sqrt","%","1/x","="};JButton potbtn,pmbtn;JPanel panel,part1,part2,part3;JTextField resulttf,memtf;JButton backspace;JButton ce;JButton c;boolean isNew=true;boolean isNextNum=false;String newResult=null;String newOperator=null;String saveValue=null;boolean isMem;Calculator(){super("计算器");//第一部分:显示结果part1=new JPanel();FlowLayout flowLayout1=new FlowLayout();flowLayout1.setVgap(0);part1.setLayout(flowLayout1);resulttf=new JTextField(22);resulttf.setEditable(false);resulttf.setHorizontalAlignment(JTextField.TRAILING);resulttf.setEnabled(true);part1.add(resulttf);part1.setBounds(10,25,250,45);//第二部分:标记是否有存储值以及backspace,ce,cpart2=new JPanel();FlowLayout flowLayout2=new FlowLayout(FlowLayout.LEFT,10,6);flowLayout2.setVgap(0);part2.setLayout(flowLayout2);memtf=new JTextField(2);memtf.setEditable(false);memtf.setHorizontalAlignment(JTextField.CENTER); memtf.setVisible(true);backspace=new JButton("Backspace"); backspace.addActionListener(this);ce=new JButton("CE");ce.addActionListener(this);c=new JButton("C");c.addActionListener(this);part2.add(memtf);part2.add(backspace);part2.add(ce);part2.add(c);part2.setBounds(3,70,300,35);part2.setVisible(true);//第三部分:各个按钮part3=new JPanel();part3.setVisible(true);part3.setBounds(10,105,250,180);part3.setLayout(new GridLayout(4,6,5,5));numbtn=new NumBtn[10];for(int i=0;i<10;i++){numbtn[i]=new NumBtn(i);numbtn[i].addActionListener(this);}operbtn=new OperBtn[4];for(int i=0;i<4;i++){operbtn[i]=new OperBtn(oper[i]);operbtn[i].addActionListener(this);}funbtn=new FunBtn[4];for (int i=0;i<4;i++){funbtn[i]=new FunBtn(fun[i]);funbtn[i].addActionListener(this);}mathbtn=new MathBtn[4];for(int i=0;i<4;i++){mathbtn[i]=new MathBtn(math[i]);mathbtn[i].addActionListener(this); }potbtn=new JButton(".");potbtn.addActionListener(this);pmbtn=new JButton("+/-");pmbtn.addActionListener(this); potbtn.setMargin(insets);pmbtn.setMargin(insets);part3.add(funbtn[0]);part3.add(numbtn[7]);part3.add(numbtn[8]);part3.add(numbtn[9]);part3.add(operbtn[0]);part3.add(mathbtn[0]);part3.add(funbtn[1]);part3.add(numbtn[4]);part3.add(numbtn[5]);part3.add(numbtn[6]);part3.add(operbtn[1]);part3.add(mathbtn[1]);part3.add(funbtn[2]);part3.add(numbtn[1]);part3.add(numbtn[2]);part3.add(numbtn[3]);part3.add(operbtn[2]);part3.add(mathbtn[2]);part3.add(funbtn[3]);part3.add(numbtn[0]);part3.add(pmbtn);part3.add(potbtn);part3.add(operbtn[3]);part3.add(mathbtn[3]);//将各个部分放置于一个面板panel=new JPanel();panel.setLayout(null);panel.add(part1);panel.add(part2);panel.add(part3);panel.setVisible(true);//主框架的设置setLayout(new BorderLayout()); getContentPane().add(panel);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setSize(276,325);setLocation(500,200);setVisible(true);setResizable(false);}public void actionPerformed(ActionEvent e){if(e.getSource() instanceof NumBtn){NumBtn bt=(NumBtn)e.getSource();if(!isNew)resulttf.setText(resulttf.getText()+bt.getNum());elseresulttf.setText(""+bt.getNum());isNew=false;isNextNum=true;}else if(e.getSource() instanceof OperBtn){OperBtn bt=(OperBtn)e.getSource();if((resulttf.getText()).equals(""))return;if((newOperator!=null)&&(isNextNum==true)){try{double num1=Double.parseDouble(newResult);double num2=Double.parseDouble(resulttf.getText());double res=0;if(newOperator.equals("+"))res=num1+num2;else if(newOperator.equals("-"))res=num1-num2;else if(newOperator.equals("*"))res=num1*num2;else if(newOperator.equals("/"))res=num1/num2;resulttf.setText(""+res);isNextNum=false;}catch(NumberFormatException e1){}catch(NullPointerException e2){}}newOperator=bt.getOper();newResult=resulttf.getText();if(isNextNum)resulttf.setText("");isNew=true;isNextNum=false;}else if(e.getSource()==mathbtn[3]){if(isNextNum==true){try{double num1=Double.parseDouble(newResult);double num2=Double.parseDouble(resulttf.getText());double res=0;if(newOperator.equals("+"))res=num1+num2;else if(newOperator.equals("-"))res=num1-num2;else if(newOperator.equals("*"))res=num1*num2;else if(newOperator.equals("/"))res=num1/num2;resulttf.setText(""+res);}catch(NumberFormatException e1){}catch(NullPointerException e2){}}newOperator=null;newResult=null;isNew=true;isNextNum=false;}else if(e.getSource()==potbtn){if(resulttf.getText().indexOf(".")!=-1)return;if(!isNew&&resulttf.getText()!="")resulttf.setText(resulttf.getText()+".");elseresulttf.setText("0.");isNew=false;isNextNum=true;}else if(e.getSource()==pmbtn){if(resulttf.getText().indexOf("-")!=-1)resulttf.setText(""+Math.abs(Double.parseDouble(resulttf.getText())));else if((resulttf.getText()!="")&&(!isNew))resulttf.setText("-"+resulttf.getText());else{resulttf.setText("-");isNew=false;}}else if(e.getSource()==funbtn[2]){if(resulttf.getText()!=""){saveValue=resulttf.getText();memtf.setText("M");isMem=true;}}else if(e.getSource()==funbtn[1]){if(isMem){resulttf.setText(saveValue);isNextNum=true;}}else if(e.getSource()==funbtn[0]){memtf.setText("");isMem=false;}else if(e.getSource()==funbtn[3]){if(resulttf.getText()!=null){double num1=Double.parseDouble(resulttf.getText());double num2=Double.parseDouble(saveValue);double res;res=num1+num2;if(isMem){resulttf.setText(""+res);}}}else if(e.getSource()==mathbtn[0]){if(!(resulttf.getText().equalsIgnoreCase("-"))&&(Double.parseDouble(resulttf.getText())>=0) ){double num1=Double.parseDouble(resulttf.getText());num1=Math.sqrt(num1);resulttf.setText(""+num1);}}else if(e.getSource()==mathbtn[1]){if((resulttf.getText()!=null)&&!(resulttf.getText().equalsIgnoreCase("-"))){double num1=Double.parseDouble(resulttf.getText());num1=num1/100;resulttf.setText(""+num1);}}else if(e.getSource()==mathbtn[2]){if((resulttf.getText()!=null)&&!(resulttf.getText().equalsIgnoreCase("-"))){double num1=Double.parseDouble(resulttf.getText());num1=1/num1;resulttf.setText(""+num1);}}else if((e.getSource()==backspace)||(e.getSource()==ce)){if(resulttf.getText()!=null){String backString;int i=resulttf.getText().length()-1;backString=resulttf.getText().substring(0,i);resulttf.setText(backString);}}else if(e.getSource()==c){resulttf.setText("");}}public static void main(String args[]){new Calculator();}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
java课程设计专业:计算机应用技术班级:0901学号:**********设计人:谢荣芳指导教师:兰方鹏一、JA V A源代码import java.awt.*;import java.awt.event.*;import java.io.*;import javax.swing.*;import javax.swing.JTextArea;import java.applet.*;import java.awt.datatransfer.*;public class myzy{ public static void main(String args[]){ MyFrame win=new MyFrame("java设计的windows窗口");}}//复数运算窗口class Complex extends Frame implements ActionListener{ TextField txt1,txt2,txt3,txt4,txt5,txt6;//声明对象Button button6,button7,button8,button9;Label label2;Box box1,box2,box3,box4,box5,box6,box7,box8,box9;//声明两个行型盒式容器box1,box2// 一个列型盒式容器box3Complex(){setLayout(new FlowLayout());txt1=new TextField(3);//对象实例化txt2=new TextField(3);txt3=new TextField(3);txt4=new TextField(3);txt5=new TextField(3);txt6=new TextField(3);label2=new Label(" ");button6=new Button("加");button7=new Button("减");button8=new Button("乘");button9=new Button("除");box1=Box.createHorizontalBox();box1.add(txt1);box1.add(new Label("+"));box1.add(txt3);box1.add(new Label("i"));box4=Box.createHorizontalBox();box4.add(label2);box5=Box.createHorizontalBox();box5.add(txt2);box5.add(new Label("+"));box5.add(txt4);box5.add(new Label("i"));box6=Box.createHorizontalBox();box6.add(new Label("="));box7=Box.createHorizontalBox();box7.add(txt5);box7.add(new Label("+"));box7.add(txt6);box7.add(new Label("i"));box8=Box.createVerticalBox();box8.add(box1);box8.add(Box.createV erticalStrut(3));box8.add(box4);box8.add(Box.createV erticalStrut(3));box8.add(box5);box8.add(Box.createV erticalStrut(3));box8.add(box6);box8.add(Box.createVerticalStrut(3));box8.add(box7);box2=Box.createVerticalBox();box2.add(button6);box2.add(Box.createV erticalStrut(3));box2.add(button7);box2.add(Box.createV erticalStrut(3));box2.add(button8);box2.add(Box.createV erticalStrut(3));box2.add(button9);box9=Box.createHorizontalBox();box9.add(box2);box9.add(Box.createV erticalStrut(35));box9.add(box8);add(box9);button6.addActionListener(this);//对象添加监视器button7.addActionListener(this);button8.addActionListener(this);button9.addActionListener(this);setSize(200,200);setVisible(true);setResizable(false);addWindowListener(new WindowAdapter()//为窗口添加监视器,保证窗口正常关闭{ public void windowClosing(WindowEvent e){ System.exit(0);}});validate();}public void actionPerformed(ActionEvent e)//实现接口方法{ double m1,m2;if(e.getSource()==button6) // 实现复数相加{ double a,b,c,d;try{ a=Double.parseDouble(txt1.getText());c=Double.parseDouble(txt2.getText());b=Double.parseDouble(txt3.getText());d=Double.parseDouble(txt4.getText());m1=a+c;m2=b+d;txt5.setText(String.valueOf(m1));txt6.setText(String.valueOf(m2));label2.setText("+");}catch(NumberFormatException ee){ txt6.setText("请输入数字字符");} }else if(e.getSource()==button7) //实现复数相减{ double a,b,c,d;try{ a=Double.parseDouble(txt1.getText());c=Double.parseDouble(txt2.getText());b=Double.parseDouble(txt3.getText());d=Double.parseDouble(txt4.getText());m1=a-c;m2=b-d;txt5.setText(String.valueOf(m1));txt6.setText(String.valueOf(m2));label2.setText("-");}catch(NumberFormatException ee){ txt6.setText("请输入数字字符");} }else if(e.getSource()==button8) //实现复数相乘{ double a,b,c,d;try{ a=Double.parseDouble(txt1.getText());c=Double.parseDouble(txt2.getText());b=Double.parseDouble(txt3.getText());d=Double.parseDouble(txt4.getText());m1=a*c-b*d;m2=a*d+b*c;txt5.setText(String.valueOf(m1));txt6.setText(String.valueOf(m2));label2.setText("*");}catch(NumberFormatException ee){ txt6.setText("请输入数字字符");}}if(e.getSource()==button9) //实现复数相除{ double a,b,c,d;try{ a=Double.parseDouble(txt1.getText());c=Double.parseDouble(txt2.getText());b=Double.parseDouble(txt3.getText());d=Double.parseDouble(txt4.getText());m1=(a*c+b*d)/(c*c+d*d);m2=(b*c-a*d)/(c*c+d*d);txt5.setText(String.valueOf(m1));txt6.setText(String.valueOf(m2));label2.setText("/");}catch(NumberFormatException ee){ txt6.setText("请输入数字字符");}}validate();}}//计算器窗口class CalculatorFrame extends Frame implements ActionListener{ TextField text2,text3,text4;//声明对象Button button1,button2,button3,button4,button5;Label label,label1;Box baseBox1,baseBox2,baseBox;//声明两个行型盒式容器baseBox1,baseBox2,一个列型盒式容器,baseBoxCalculatorFrame(){setLayout(new FlowLayout());text2=new TextField(10);//为对象分配内存text3=new TextField(10);text4=new TextField(10);label=new Label(" ");label1=new Label("=");label.setBackground(Color.yellow);label1.setBackground(Color.green);button1=new Button("+");button2=new Button("-");button3=new Button("*");button4=new Button("/");button5=new Button("复数运算");baseBox1=Box.createHorizontalBox();//添加的组件之间插入水平支撑控制组件之间距离baseBox1.add(Box.createHorizontalStrut(10));baseBox1.add(text2);baseBox1.add(Box.createHorizontalStrut(10));baseBox1.add(label);baseBox1.add(Box.createHorizontalStrut(10));baseBox1.add(text3);baseBox1.add(Box.createHorizontalStrut(10));baseBox1.add(label1);baseBox1.add(Box.createHorizontalStrut(10));baseBox1.add(text4);baseBox1.add(Box.createHorizontalStrut(10));baseBox2=Box.createHorizontalBox();//添加的组件之间插入垂直支撑控制组件之间距离baseBox2.add(Box.createHorizontalStrut(10));baseBox2.add(button1);baseBox2.add(Box.createHorizontalStrut(10));baseBox2.add(button2);baseBox2.add(Box.createHorizontalStrut(10));baseBox2.add(button3);baseBox2.add(Box.createHorizontalStrut(10));baseBox2.add(button4);baseBox2.add(Box.createHorizontalStrut(10));baseBox2.add(button5);baseBox2.add(Box.createHorizontalStrut(10));baseBox =Box.createV erticalBox();baseBox.add(Box.createVerticalStrut(10));baseBox.add(baseBox1);baseBox.add(Box.createVerticalStrut(10));baseBox.add(baseBox2);baseBox.add(Box.createVerticalStrut(10));add(baseBox);button1.addActionListener(this);//对象添加监视器button2.addActionListener(this);button3.addActionListener(this);button4.addActionListener(this);button5.addActionListener(this);setBounds(300,300,360,120);setVisible(true);setResizable(false);addWindowListener (new WindowAdapter()//增加适配器使窗口正常关闭{ public void windowClosing(WindowEvent e){System.exit(0);}});validate();}public void actionPerformed(ActionEvent e)//实现接口方法{ double n;if(e.getSource()==button1)//实现加法运算{ double n1,n2;try{ n1=Double.parseDouble(text2.getText());n2=Double.parseDouble(text3.getText());n=n1+n2;text4.setText(String.valueOf(n));label.setText("+");}catch(NumberFormatException ee){ text4.setText("请输入数字字符");}}else if(e.getSource()==button2)//实现减法运算{ double n1,n2;try{ n1=Double.parseDouble(text2.getText());n2=Double.parseDouble(text3.getText());n=n1-n2;text4.setText(String.valueOf(n));label.setText("-");}catch(NumberFormatException ee){ text4.setText("请输入数字字符");}}else if(e.getSource()==button3)//实现乘法运算{ double n1,n2;try{ n1=Double.parseDouble(text2.getText());n2=Double.parseDouble(text3.getText());n=n1*n2;text4.setText(String.valueOf(n));label.setText("*");}catch(NumberFormatException ee){ text4.setText("请输入数字字符");}}else if(e.getSource()==button4)//实现除法运算{ double n1,n2;try{ n1=Double.parseDouble(text2.getText());n2=Double.parseDouble(text3.getText());n=n1/n2;text4.setText(String.valueOf(n));label.setText("/");}catch(NumberFormatException ee){ text4.setText("请输入数字字符");}}else if(e.getSource()==button5)//实现复数运算{Complex fushu=new Complex();fushu.setTitle("复数运算");//设置窗口标题toFront();}validate();//保证组件正常显示}}//标准的windows窗口class MyFrame extends Frame implements ActionListener,ItemListener{ MenuBar menubar;//声明对象Menu menu1,menu2,menu3;MenuItem item1,item2,item3,item4,item5,item6,item7,item8;Clipboard clipboard=null; //声明一个剪切板对象TextArea text,text1;BufferedReader in;FileReader file_reader;BufferedWriter out;FileWriter tofile;FileDialog filedialog_save,filedialog_load;Choice list;JTextArea text0;MyFrame(String s){ setTitle(s);//设置窗口标题Toolkit tool=getToolkit();Dimension dim=tool.getScreenSize();setBounds(100,100,dim.width/2,dim.height/2);//设置窗口出现的初始位置clipboard=getToolkit().getSystemClipboard();text1=new TextArea(10,20); //为对象分配内存,使用new和构造方法menubar=new MenuBar();menu1=new Menu("文件");menu2=new Menu("编辑");menu3=new Menu("工具");item1=new MenuItem("打开");item1.setShortcut(new MenuShortcut(KeyEvent.VK_O));item2=new MenuItem("保存");item2.setShortcut(new MenuShortcut(KeyEvent.VK_S));item3=new MenuItem("退出");item3.setShortcut(new MenuShortcut(KeyEvent.VK_E));item4=new MenuItem("剪切");item4.setShortcut(new MenuShortcut(KeyEvent.VK_C));item5=new MenuItem("复制");item5.setShortcut(new MenuShortcut(KeyEvent.VK_P));item6=new MenuItem("粘贴");item6.setShortcut(new MenuShortcut(KeyEvent.VK_V));item7=new MenuItem("计算器");item7.setShortcut(new MenuShortcut(KeyEvent.VK_Q));item1.addActionListener(this);//将窗口作为它的监视器item2.addActionListener(this);item3.addActionListener(this);item4.addActionListener(this);item5.addActionListener(this);item6.addActionListener(this);item7.addActionListener(this);menu1.add(item1);//调用add()方法添加组件menu1.add(item2);menu1.add(item3);menu2.add(item4);menu2.add(item5);menu2.add(item6);menu3.add(item7);menubar.add(menu1);menubar.add(menu2);menubar.add(menu3);setMenuBar(menubar);//将菜单条放置到窗口add(text1);filedialog_save=new FileDialog(this,"保存对话框",FileDialog.SA VE); filedialog_load=new FileDialog(this,"打开对话框",FileDialog.LOAD);filedialog_load.addWindowListener(new WindowAdapter()//保存对话框增加适配器{public void windowClosing(WindowEvent e){ filedialog_load.setVisible(false);}});filedialog_save.addWindowListener(new WindowAdapter()//打开对话框增加适配器{public void windowClosing(WindowEvent e){ filedialog_save.setVisible(false);}});addWindowListener(new WindowAdapter() //增加适配器使窗口正常关闭{ public void windowActivated(WindowEvent e){}public void windowClosing(WindowEvent e){ System.exit(0);}});list=new Choice();text0=new JTextArea();text0.setForeground(Color.blue);GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();String fontName[]=ge.getAvailableFontFamilyNames();for(int i=0;i<fontName.length;i++){ list.add(fontName[i]); }add(list,BorderLayout.NORTH);add(text0,BorderLayout.CENTER);text0.setForeground(Color.red);list.addItemListener(this);setVisible(true);//窗口可见setResizable(true);//可调整大小validate();//保证组件正确显示}public void itemStateChanged(ItemEvent e){ String name=list.getSelectedItem();Font f=new Font(name,Font.BOLD,32);text0.setFont(f);text0.setText("");}public void actionPerformed(ActionEvent e)//实现接口方法{ if(e.getSource()==item1) //使用文件对话框打开文件{ filedialog_load.setVisible(true);text0.setText(null);String s;if(filedialog_load.getFile()!=null){try{ File file= new File(filedialog_load.getDirectory(),filedialog_load.getFile());file_reader=new FileReader(file);in=new BufferedReader(file_reader);while((s=in.readLine())!=null)text0.append(s+'\n');in.close();file_reader.close();}catch(IOException e2){System.out.println("打开失败");}}}else if(e.getSource()==item2) //使用文件对话框保存文件{ filedialog_save.setVisible(true);if(filedialog_save.getFile()!=null){try{File file=new File(filedialog_save.getDirectory(),filedialog_save.getFile());tofile=new FileWriter(file);out=new BufferedWriter(tofile);out.write(text.getText(),0,(text.getText()).length());out.close();tofile.close();}catch(IOException e2){}}}else if(e.getSource()==item3) //实现退出功能{ System.exit(0);}else if(e.getSource()==item4) //实现剪切功能{ String temp=text0.getSelectedText();StringSelection text=new StringSelection(temp);clipboard.setContents(text,null);int start=text0.getSelectionStart();int end =text0.getSelectionEnd();text0.replaceRange("",start,end) ; //从text1中删除被选取的文本}else if(e.getSource()==item5) //实现复制功能{ String temp=text0.getSelectedText(); //得到鼠标拖动选取的文本StringSelection text=new StringSelection(temp);clipboard.setContents(text,null);}else if(e.getSource()==item6) //实现粘贴功能{ Transferable contents=clipboard.getContents(this);DataFlavor flavor= DataFlavor.stringFlavor;if( contents.isDataFlavorSupported(flavor))try{ String str;str=(String)contents.getTransferData(flavor);int pos=text0.getCaretPosition();text0.insert(str,pos);}catch(Exception ee){}}else if(e.getSource()==item7)//实现计算器功能{CalculatorFrame co=new CalculatorFrame();co.setTitle("计算器");//设置窗口标题toFront();}}}二、运行过程及其结果的主要截图图1 打开文件及菜单项图2 保存对话框图3 计算器窗口和复数运算窗口三、课程设计总结这次的课程设计,使我对java有了进一步的了解和体会。