J2ME计算器源码

合集下载

javascript代码实现简易计算器

javascript代码实现简易计算器

javascript代码实现简易计算器本⽂实例为⼤家分享了javascript实现简易计算器的具体代码,供⼤家参考,具体内容如下编辑了⼏个⼩时研发了⼀个简易好理解的计算器。

不停改Bug,终于改好了。

这是样式这是Css部分<style>#box {background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);width: 500px;height: 420px;margin: auto;margin-top: 200px;position: relative;}.reckon {width: 280px;height: 200px;background-image: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%);;position: absolute;top: 100px;left: 100px;border: 5px solid #2a2b2c}#input1 {background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);border: none;width: 220px;height: 8px;float: right;margin-top: 10px;margin-right: 20px;outline: none;padding: 10px}ul li {float: left;list-style: none;margin: 4px 2px;border-radius: 3px;background-image: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);box-shadow: 2px 2px #ccc;color: #fff;font-weight: "楷体";width: 50px;height: 30px;text-align: center;line-height: 30px;}ul {margin-top: 5px;}ul li:hover {opacity: 0.7;}</style>这是HTML部分<div id="box"><div class="reckon" id="reckon"><input type="text" id="input1"><ul><li class="num">7</li><li class="num">8</li><li class="num">9</li><li class="opcr">+</li><li class="num">4</li><li class="num">5</li><li class="num">6</li><li class="opcr">- </li><li class="num">1</li><li class="num">2</li><li class="num">3</li><li class="opcr">*</li><li class="num">0</li><li id="returnZero">C</li><li id="resule">=</li><li class="opcr">/</li></ul></div></div>/* 定义两个标签来存放符号跟第⼀个值*/<input type="text" id="text1" style="display:none"><input type="text" id="per" style="display:none">html部分的话就是吧所有数字定义为⼀个class名字,把所有运算符号定义为⼀个class 以及定义两个input来存放运算符<script>lis = document.querySelectorAll("#box ul .num")//获取所有的数字opcr = document.querySelectorAll("#box ul .opcr")//获取运算符for (var i = 0; i < lis.length; i++) { //遍历所有的数字lis[i].onclick = function () {input1.value += parseInt(this.innerHTML)//点击input1显⽰}}//遍历所有的运算符for (let i = 0; i < opcr.length; i++) {opcr[i].onclick = function () {if (text1.value == "") {//当存放第⼀个值为空时候text1.value = input1.value//存放第⼀个值input1.value = "" //input框⾥的值为空per.value = this.innerHTML; //存放符号的值为空} else {text1.value = eval(text1.value + per.value + input1.value)//不是空的时候计算per.value = this.innerHTML;//存放符号的值为点击的值input1.value = ""//input框⾥的值为空}}}//等于resule.onclick = function () {input1.value = eval(text1.value + per.value + input1.value)//计算⾥⾯的值 per.value = "" //清空存放per的值text1.value = ""//input框⾥的值为空}//点击清空所有returnZero.onclick = function () {input1.value = ""per.value = ""text1.value = ""}</script>完整部分<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"><title>简易计算器</title><style>#box {background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%); width: 500px;height: 420px;margin: auto;margin-top: 200px;position: relative;}.reckon {width: 280px;height: 200px;background-image: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%); ;position: absolute;top: 100px;left: 100px;border: 5px solid #2a2b2c}#input1 {background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);border: none;width: 220px;height: 8px;float: right;margin-top: 10px;margin-right: 20px;outline: none;padding: 10px}ul li {float: left;list-style: none;margin: 4px 2px;border-radius: 3px;background-image: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%); box-shadow: 2px 2px #ccc;color: #fff;font-weight: "楷体";width: 50px;height: 30px;text-align: center;line-height: 30px;}ul {margin-top: 5px;}opacity: 0.7;}</style></head><body><div id="box"><div class="reckon" id="reckon"><input type="text" id="input1"><ul><li class="num">7</li><li class="num">8</li><li class="num">9</li><li class="opcr">+</li><li class="num">4</li><li class="num">5</li><li class="num">6</li><li class="opcr">- </li><li class="num">1</li><li class="num">2</li><li class="num">3</li><li class="opcr">*</li><li class="num">0</li><li id="returnZero">C</li><li id="resule">=</li><li class="opcr">/</li></ul></div></div><input type="text" id="text1" style="display:block"><input type="text" id="per" style="display:block"><script>lis = document.querySelectorAll("#box ul .num")//获取所有的数字opcr = document.querySelectorAll("#box ul .opcr")//获取+——*/for (var i = 0; i < lis.length; i++) { //遍历所有的数字lis[i].onclick = function () {input1.value += parseInt(this.innerHTML)//点击input1显⽰}}//遍历所有的+——*/for (let i = 0; i < opcr.length; i++) {opcr[i].onclick = function () {if (text1.value == "") {//当存放第⼀个值为空时候text1.value = input1.value//存放第⼀个值input1.value = "" //input框⾥的值为空per.value = this.innerHTML; //存放符号的值为空} else {text1.value = eval(text1.value + per.value + input1.value)//不是空的时候计算值 per.value = this.innerHTML;//存放符号的值为点击的值input1.value = ""//input框⾥的值为空}}}//等于resule.onclick = function () {input1.value = eval(text1.value + per.value + input1.value)//计算⾥⾯的值per.value = "" //清空存放per的值text1.value = ""//input框⾥的值为空}//点击清空所有returnZero.onclick = function () {input1.value = ""per.value = ""text1.value = ""}</script></html>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

java计算器程序代码

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)); }}}。

J2ME综合--关于J2ME中RMS的使用解析

J2ME综合--关于J2ME中RMS的使用解析

[摘要] 很多刚刚开始学习J2ME的新人总是抱怨在这方面的资料很少,或者是针对性不强。

因此,我想把自己在这方面的一些学习心得和大家交流一下。

[关键字] J2ME RMS使用解析在J2ME中,RMS作为唯一的永久性存储工具,其重要性是不言而喻的。

但是很多刚刚开始学习J2ME的新人总是抱怨在这方面的资料很少,或者是针对性不强。

因此,我想把自己在这方面的一些学习心得和大家交流一下。

RMS即Record Manager System,在手机应用中常常作为得分记录、游戏信息存储等的工具使用。

RMS的使用可以分为两个部分:一、单一记录的构造;二、RecordStore的使用和操作。

下面就这两方面进行详细说明。

一、单一记录的构造。

我们在存储记录时可能需要记录很多相似的条目,在这里我们可以把这种结构看成数据库,我们在这一步就是要构造数据库中的一行,即单一记录的构造。

程序的源码如下:package ual;import java.io.ByteArrayInputStream;//要使用到的各种输入输出流import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;public class Appointment {//单一记录的类名private int int1;//private int int2;//private long long1;private String str1;//str1作为保留字段,记录检索的关键字private String str2;//private String str3;//private boolean WroteFlag;//public Appointment(){}public Appointment(int _int1,int _int2,long _long1,String _str1,String _str2,String _str3,boolean _WroteFlag){this.int1 = _int1;//写入RMS的构造函数this.int2 = _int2;this.long1 = _long1;this.str1 = _str1;this.str2 = _str2;this.str3 = _str3;this.WroteFlag = _WroteFlag;}public Appointment(byte[] rec){initAppointmnet(rec);//读取RMS内容的构造函数}public byte[] toBytes(){ //写成字节byte[] data = null;try {ByteArrayOutputStream baos = new ByteArrayOutputStream();DataOutputStream dos = new DataOutputStream(baos);dos.writeInt(int1);dos.writeInt(int2);dos.writeLong(long1);dos.writeUTF(str1);dos.writeUTF(str2);dos.writeUTF(str3);dos.writeBoolean(WroteFlag);data = baos.toByteArray();baos.close();dos.close();} catch (Exception e){e.printStackTrace();}return data;}public void initAppointmnet(byte[] rec){ //从字节读取内容ByteArrayInputStream bais = new ByteArrayInputStream(rec);DataInputStream dis = new DataInputStream(bais);try {int1 = dis.readInt();int2 = dis.readInt();long1 = dis.readLong();str1 = dis.readUTF();str2 = dis.readUTF();str3 = dis.readUTF();WroteFlag = dis.readBoolean();} catch (Exception e){e.printStackTrace();}}public int getInt1(){ //int return int1;}public int getInt2(){return int2;}public long getLong1(){ return long1;}public String getStr1(){ //String return str1;}public String getStr2(){ //String return str2;}public String getStr3(){return str3;}public boolean getWroteFlag(){ //返回写入标志return WroteFlag;}}这个类的使用保证了我们在使用流时,内容的写入和输出。

J2ME程序设计实例教程(第03章)

J2ME程序设计实例教程(第03章)

keyPressed(int keyCode) keyReleased(int keyCode) keyRepeated(int keyCode) pointerPressed(int x, int y) pointerReleased(int x, in ty) pointerDragged(int x, int y)
前4个方法用于计算Item的最小尺寸和首选尺寸,将被 Form的布局管理器调用。paint方法用于绘制Item外观。
3.1 知识点——Item遍历
用户可以通过方向键把焦点从一个Item组件转移到 另一个Item组件,前一个组件失去了焦点,后一个组件 获得了焦点,称为外部遍历。 如果用户按方向键,焦点并没有从当前的Item组件 转移到其他的Item组件,只是在当前组件的内部转移, 当前组件依然具有焦点,称为内部遍历。
setColor(int rgb) setColor(int red,int gree,int blue) drawLine(int x0,int y0,int x1,int y1) drawRect(int x, int y, int w, int h) fillRect(int x, int y, int w, int h) drawString(String text, int x, int y, drawChar(char character, int x, int y, drawChars(char[] data, int offset, int x, int y, int anchr)
int getMinContentHeight() int getMinContentWidth() int getPrefContentHeight(int w) int getPrefContentWidth(int h) void paint(Graphics g, int w, int h)

Java计算器源代码(已成功运行)汇总

Java计算器源代码(已成功运行)汇总
Java计算器程序代码
以下为代码:
importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
private booleandotExist, operated, equaled; //帮助运算的布尔变量
private double storedNumber; //目前的结果private char lastOperator; //表示上一运算符private JTextField operation; //结果栏
private JButton dot, plus, minus, multi, div, sqrt, equal, changePN, clear; //运算符
private JButton[] numbers; //数字
//构造者
public Calculator(
{
setTitle("Calculator";
//初始化变量
dotExist = false; //表示当前的数是否有小数点
operated = false; //表示任意运算符是否被按下equaled = false; //表示等号是否被按下storedNumber = 0;
else if (lastOperator == 's' storedNumber = Math.sqrt(currentNumber; else if (lastOperator == '=' && equaled storedNumber = currentNumber; operation.setText("" + storedNumber; operated = true; lastOperator = operator; } //快捷使用GridBagLayout的方法private void addComponent(GridBagLayout layout, Component component, int row, int col, int width, int height { GridBagConstraints constraints=new GridBagConstraints(; constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(10, 2, 10, 2; constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = col; constraints.gridy = row; constraints.gridwidth = width; constraints.gridheight = height; layout.setConstraints(component, constraints;

J2ME 计算器高层界面源码

J2ME 计算器高层界面源码
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
return;
}
double result = 0.0;
case 0: result = d1 + d2; break;
case 1: result = d1 - d2; break;
case 2: result = d1 * d2; break;
case 3: result = d1 / d2; break;
/** 接收第一个参数. */
private final TextField arg1 = new TextField("第一个参数", "", 20, TextField.DECIMAL);
/** 接收第二个参数*/
private final TextField arg2 = new TextField("第二个参数", "", 20, TextField.DECIMAL);
alert.setString("No Argument");
Display.getDisplay(this).setCurrent(alert);
}
double n = 0.0;
try {
n = Double.parseDouble(s);
/** 显示结果*/
private final TextField ret = new TextField("结果", "", 20, TextField.UNEDITABLE);

java计算器源代码(仿win7)

java计算器源代码(仿win7)

java计算器源代码(仿win7)import java.awt.*;import javax.swing.*;import java.awt.event.*;class Cal extends JFrame implements ActionListener,MouseListener{JMenuBar menubar;JMenu menu_check,menu_edit,menu_help;JMenuItem menuitem_science,menuitem_check,menuitem_exit,menuitem_copy,menuitem_paste,menuitem1_copy,menuitem1_paste,menuitem_chelp,menuitem_about;JCheckBoxMenuItem menuitem_standard;JTextField ta1;int x,result2;double op1,op2,opall;private boolean end=false,flag=false,add=false,sub=false,cheng=false,chu=false,flagop2=false;JButton b_mc,b_mr,b_ms,b_mjia,b_mjian,b_tui,b_ce,b_c,b_jj,b_dui,b_7,b_8,b_9,b_chu,b_baifenhao,b_4,b_5,b_6,b_cheng,b_daoshu,b_1,b_2,b_3,b_jian,b_0,b_dian,b_jia,b_dengyu;JPanel p_all,p_button1,p_button2,p_txt,p1,p2,p3,p4,p5;private String str,resultstr;JPopupMenu popupmenu;Container con=this.getContentPane();Font font=new Font("微软雅黑",Font.PLAIN,12);Color color=new Color(120,220,120);Cal(String s){super(s);setSize(220,315);setResizable(false);setVisible(true);Dimension scr=Toolkit.getDefaultToolkit().getScreenSize();Dimension frm=this.getSize();setLocation((scr.width-frm.width)/2,(scr.height-frm.height)/2);Toolkit tk=Toolkit.getDefaultToolkit();//程序默认图标设置setIconImage(tk.createImage("D:\\sd.jpg"));setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//-----------------------------------------------------------------制作框架结构------------------------- //---------------------------------------菜单栏---------------------------menubar=new JMenuBar();menubar.setPreferredSize(new Dimension(frm.width,19));menu_check=new JMenu("查看(V)");menu_check.setFont(font);menu_check.setForeground(Color.black);menuitem_standard=new JCheckBoxMenuItem("标准型",true);menuitem_standard.setFont(font);menuitem_standard.setForeground(Color.black);menuitem_science=new JMenuItem("科学型");menuitem_science.setFont(font);menuitem_science.setForeground(Color.black);menuitem_check=new JMenuItem("查看分组");menuitem_check.setFont(font);menuitem_check.setForeground(Color.black);menuitem_exit=new JMenuItem("退出");menuitem_exit.setFont(font);menuitem_exit.setForeground(Color.black);menuitem_exit.addActionListener(this);menu_check.add(menuitem_standard);menu_check.add(menuitem_science);menu_check.addSeparator();menu_check.add(menuitem_check);menu_check.addSeparator();menu_check.add(menuitem_exit);menubar.add(menu_check);menu_edit=new JMenu("编辑(E)");menu_edit.setFont(font);menu_edit.setForeground(Color.black);menu_edit.setMnemonic(KeyEvent.VK_E);menuitem_copy=new JMenuItem("复制(C) ");menuitem_copy.setFont(font);menuitem_copy.setForeground(Color.black);menuitem_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_M ASK));menuitem_copy.addActionListener(this);menuitem_paste=new JMenuItem("粘贴(P) ");menuitem_paste.setFont(font);menuitem_paste.setForeground(Color.black);menuitem_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_M ASK));menuitem_paste.addActionListener(this);menu_edit.add(menuitem_copy);menu_edit.add(menuitem_paste);menubar.add(menu_edit);menu_help=new JMenu("帮助(H)");menu_help.setFont(font);menu_help.setForeground(Color.black);menuitem_chelp=new JMenuItem("查看帮助");menuitem_chelp.setFont(font);menuitem_chelp.setForeground(Color.black);menuitem_about=new JMenuItem("关于计算器");menuitem_about.setFont(font);menuitem_about.setForeground(Color.black);menuitem_about.addActionListener(this);menu_help.add(menuitem_chelp);menu_help.addSeparator();menu_help.add(menuitem_about);menubar.add(menu_help);setJMenuBar(menubar);//--------------------------------------文本框----------------------------------ta1=new JTextField("0");ta1.setFont(new Font("微软雅黑",Font.PLAIN,13));ta1.setEditable(false);//ta1.setOpaque(false);ta1.setHorizontalAlignment(JTextField.RIGHT);ta1.setPreferredSize(new Dimension((frm.width-26),45));ta1.addMouseListener(this);p_all=new JPanel();p_all.setPreferredSize(new Dimension((frm.width-6),250));//p_all.setBackground(color);p_all.setLayout(new FlowLayout(FlowLayout.CENTER,0,3));p_txt=new JPanel();p_txt.setPreferredSize(new Dimension((frm.width-6),53));p_txt.setLayout(new FlowLayout(FlowLayout.CENTER,0,7));p_txt.add(ta1);p_all.add(p_txt);con.add(p_all,BorderLayout.CENTER);//-------------------------------------按钮区----------------------------------p_button1=new JPanel();p_button1.setPreferredSize(new Dimension((frm.width-25),131)); p_button1.setLayout(new FlowLayout(FlowLayout.LEFT,0,3));p_all.add(p_button1);p1=new JPanel();p1.setPreferredSize(new Dimension((frm.width-25),127));p1.setLayout(new GridLayout(4,5,5,6));b_mc=new JButton("MC");b_mc.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mc.setMargin(new Insets(0,0,0,0));b_mc.setForeground(Color.blue);b_mc.addActionListener(this);b_mr=new JButton("MR");b_mr.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mr.setMargin(new Insets(0,0,0,0));b_mr.setForeground(Color.blue);b_mr.addActionListener(this);b_ms=new JButton("MS");b_ms.setFont(new Font("微软雅黑",Font.PLAIN,11));b_ms.setMargin(new Insets(0,0,0,0));b_ms.setForeground(Color.blue);b_ms.addActionListener(this);b_mjia=new JButton("M+");b_mjia.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mjia.setMargin(new Insets(0,0,0,0));b_mjia.setForeground(Color.blue);b_mjia.addActionListener(this);b_mjian=new JButton("M-");b_mjian.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_mjian.setMargin(new Insets(0,0,0,0));b_mjian.setForeground(Color.blue);b_mjian.addActionListener(this);b_tui=new JButton("←");b_tui.setFont(new Font("微软雅黑",Font.BOLD,14));b_tui.setMargin(new Insets(0,0,0,0));b_tui.addActionListener(this);b_tui.setForeground(Color.red);b_ce=new JButton("CE");b_ce.setFont(new Font("微软雅黑",Font.PLAIN,11));b_ce.setMargin(new Insets(0,0,0,0));b_ce.setForeground(Color.red);b_ce.addActionListener(this);b_c=new JButton("C");b_c.setFont(new Font("微软雅黑",Font.PLAIN,11));b_c.setMargin(new Insets(0,0,0,0));b_c.setForeground(Color.red);b_c.addActionListener(this);b_jj=new JButton("±");b_jj.setFont(new Font("微软雅黑",Font.PLAIN,14));b_jj.setMargin(new Insets(0,0,0,0));b_jj.setForeground(Color.red);b_jj.addActionListener(this);b_dui=new JButton("√");b_dui.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_dui.setMargin(new Insets(0,0,0,0));b_dui.setForeground(Color.red);b_dui.addActionListener(this);b_7=new JButton("7");b_7.setFont(new Font("微软雅黑",Font.PLAIN,14));b_7.setMargin(new Insets(0,0,0,0));b_7.setForeground(Color.blue);b_7.setMnemonic(KeyEvent.VK_7);b_7.addActionListener(this);b_8=new JButton("8");b_8.setFont(new Font("微软雅黑",Font.PLAIN,14));b_8.setMargin(new Insets(0,0,0,0));b_8.setForeground(Color.blue);b_8.setMnemonic(KeyEvent.VK_8);b_8.addActionListener(this);b_9=new JButton("9");b_9.setMargin(new Insets(0,0,0,0));b_9.setForeground(Color.blue);b_9.setMnemonic(KeyEvent.VK_9);b_9.addActionListener(this);b_chu=new JButton("/");b_chu.setFont(new Font("微软雅黑",Font.PLAIN,14));b_chu.setMargin(new Insets(0,0,0,0));b_chu.setForeground(Color.red);b_chu.addActionListener(this);b_baifenhao=new JButton("%");b_baifenhao.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_baifenhao.setMargin(new Insets(0,0,0,0));b_baifenhao.setForeground(Color.blue);b_baifenhao.addActionListener(this);b_4=new JButton("4");b_4.setFont(new Font("微软雅黑",Font.PLAIN,14));b_4.setMargin(new Insets(0,0,0,0));b_4.setForeground(Color.blue);b_4.setMnemonic(KeyEvent.VK_4);b_4.addActionListener(this);b_5=new JButton("5");b_5.setFont(new Font("微软雅黑",Font.PLAIN,14));b_5.setMargin(new Insets(0,0,0,0));b_5.setForeground(Color.blue);b_5.setMnemonic(KeyEvent.VK_5);b_5.addActionListener(this);b_6=new JButton("6");b_6.setFont(new Font("微软雅黑",Font.PLAIN,14));b_6.setMargin(new Insets(0,0,0,0));b_6.setForeground(Color.blue);b_6.setMnemonic(KeyEvent.VK_6);b_6.addActionListener(this);b_cheng=new JButton("*");b_cheng.setFont(new Font("微软雅黑",Font.PLAIN,14));b_cheng.setMargin(new Insets(0,0,0,0));b_cheng.setForeground(Color.red);b_cheng.addActionListener(this);b_daoshu=new JButton("1/x");b_daoshu.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_daoshu.setMargin(new Insets(0,0,0,0));b_daoshu.setForeground(Color.blue);b_daoshu.addActionListener(this);b_1=new JButton("1");b_1.setMargin(new Insets(0,0,0,0));b_1.setForeground(Color.blue);b_1.setMnemonic(KeyEvent.VK_1);b_1.addActionListener(this);b_2=new JButton("2");b_2.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_2.setMargin(new Insets(0,0,0,0));b_2.setForeground(Color.blue);b_2.setMnemonic(KeyEvent.VK_2);b_2.addActionListener(this);b_3=new JButton("3");b_3.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_3.setMargin(new Insets(0,0,0,0));b_3.setForeground(Color.blue);b_3.setMnemonic(KeyEvent.VK_3);b_3.addActionListener(this);b_jian=new JButton("-");b_jian.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_jian.setMargin(new Insets(0,0,0,0));b_jian.setForeground(Color.red);b_jian.addActionListener(this);b_0=new JButton("0");b_0.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_0.setMargin(new Insets(0,0,0,0));b_0.setPreferredSize(new Dimension(75,27));b_0.setForeground(Color.blue);b_0.setMnemonic(KeyEvent.VK_0);b_0.addActionListener(this);JLabel L1=new JLabel();L1.setPreferredSize(new Dimension(5,3));b_dian=new JButton(".");b_dian.setFont(new Font("微软雅黑",Font.BOLD,14)); b_dian.setMargin(new Insets(0,0,0,0));b_dian.setPreferredSize(new Dimension(35,27));b_dian.setForeground(Color.blue);b_dian.addActionListener(this);JLabel L2=new JLabel();L2.setPreferredSize(new Dimension(5,3));b_jia=new JButton("+");b_jia.setFont(new Font("微软雅黑",Font.BOLD,14)); b_jia.setMargin(new Insets(0,0,0,0));b_jia.setPreferredSize(new Dimension(35,27));b_jia.setForeground(Color.red);b_jia.addActionListener(this);b_dengyu=new JButton("=");b_dengyu.setFont(new Font("微软雅黑",Font.BOLD,22));b_dengyu.setMargin(new Insets(0,0,0,0));b_dengyu.setPreferredSize(new Dimension(35,60));b_dengyu.setForeground(Color.blue);b_dengyu.addActionListener(this);p1.add(b_mc);p1.add(b_mr);p1.add(b_ms);p1.add(b_mjia);p1.add(b_mjian);p1.add(b_tui);p1.add(b_ce);p1.add(b_c);p1.add(b_jj);p1.add(b_dui);p1.add(b_7);p1.add(b_8);p1.add(b_9);p1.add(b_chu);p1.add(b_baifenhao);p1.add(b_4);p1.add(b_5);p1.add(b_6);p1.add(b_cheng);p1.add(b_daoshu);p_button1.add(p1);p_button2=new JPanel();p_button2.setPreferredSize(new Dimension((frm.width-24),65)); p_button2.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));p_all.add(p_button2);p2=new JPanel();p2.setPreferredSize(new Dimension(156,65));p2.setLayout(new FlowLayout(FlowLayout.LEFT,0,1));p3=new JPanel();p3.setPreferredSize(new Dimension(39,62));p3.setLayout(new FlowLayout(FlowLayout.LEFT,4,0));p_button2.add(p2);p_button2.add(p3);p4=new JPanel();p4.setPreferredSize(new Dimension(156,27));p4.setLayout(new GridLayout(1,4,5,5));p5=new JPanel();p5.setPreferredSize(new Dimension(156,39));p5.setLayout(new FlowLayout(FlowLayout.LEFT,0,5));p2.add(p4);p2.add(p5);p4.add(b_1);p4.add(b_2);p4.add(b_3);p4.add(b_jian);p5.add(b_0);p5.add(L1);p5.add(b_dian);p5.add(L2);p5.add(b_jia);p3.add(b_dengyu);//---------------------------------------快捷菜单对象-------------------------popupmenu=new JPopupMenu(); //快捷菜单对象menuitem1_copy=new JMenuItem("复制");menuitem1_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_ MASK));menuitem1_copy.addActionListener(this); //监视鼠标右击菜单”复制“popupmenu.add(menuitem1_copy);menuitem1_paste=new JMenuItem("粘贴");menuitem1_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));menuitem1_paste.addActionListener(this); //监视鼠标右击菜单”粘贴“popupmenu.add(menuitem1_paste);ta1.add(popupmenu);con.validate();validate();}//---------------------------------------功能区------------------------------------public void actionPerformed(ActionEvent e){if(e.getSource()==menuitem_about){JOptionPane.showMessageDialog(null,"这是一个模仿win7的计算器!欢迎改进,\n创作者:钟作明","仿win7计算器",RMATION_MESSAGE);}if(e.getSource()==menuitem1_copy){ta1.selectAll();ta1.copy();}else if(e.getSource()==menuitem1_paste){ta1.setEditable(true);ta1.setText("");ta1.paste();ta1.setEditable(false);}else if(e.getSource()==menuitem_copy){ta1.selectAll();ta1.copy();}else if(e.getSource()==menuitem_paste){ta1.setEditable(true);ta1.setText("");ta1.paste();ta1.setEditable(false);}else if(e.getSource()==menuitem_exit){System.exit(0);}else if(e.getSource()==b_ce){ta1.setEditable(true);ta1.setText("0");ta1.setEditable(false);}else if(e.getSource()==b_c){ta1.setEditable(true);ta1.setText("0");ta1.setEditable(false);}else if(e.getSource()==b_tui){String str=ta1.getText();StringBuffer s=new StringBuffer(str);int L=s.length();try{if(L!=1){s=s.deleteCharAt(L-1);}else{s=new StringBuffer("0");}}catch(Exception e1){}ta1.setText(String.valueOf(s));}//---------------------------------------------数字键----------------------------- if(e.getSource()==b_1){addString(1);}else if(e.getSource()==b_2){addString(2);}else if(e.getSource()==b_3){addString(3);}else if(e.getSource()==b_4){addString(4);}else if(e.getSource()==b_5){addString(5);}else if(e.getSource()==b_6){addString(6);}else if(e.getSource()==b_7){addString(7);}else if(e.getSource()==b_8){addString(8);}else if(e.getSource()==b_9){addString(9);}else if(e.getSource()==b_0){addString(0);}else if(e.getSource()==b_dian){StringBuffer s1=new StringBuffer(ta1.getText());StringBuffer dian=new StringBuffer(".");if(String.valueOf(s1).indexOf(".")==-1){s1.append(dian);}ta1.setText(String.valueOf(s1));}else if(e.getSource()==b_jj){String txt=ta1.getText();int result=Integer.parseInt(txt);if(txt.indexOf("-")==-1&&txt.length()>0){if(result!=0){txt="-"+txt;}}else{StringBuffer txt1=new StringBuffer(txt);txt1=txt1.deleteCharAt(0);txt=String.valueOf(txt1);}ta1.setText(txt);}else if(e.getSource()==b_dui){str=ta1.getText();Double d=Double.parseDouble(str);if(d>=0){double d1=Math.sqrt(d);String s = String.valueOf(d1);if(s.endsWith(".0")==true){int z=(int)d1;str=String.valueOf(z);}else{str=String.valueOf(d1);}ta1.setText(str);}else{JOptionPane.showMessageDialog(null,"根号底数不能为负数","提醒", RMATION_MESSAGE);}end=true;}else if(e.getSource()==b_baifenhao){str=ta1.getText();Double d=Double.parseDouble(str);ta1.setText(""+d/100);end=true;}else if(e.getSource()==b_daoshu){str=ta1.getText();Double d=Double.parseDouble(str);if(d!=0){ta1.setText(""+1/d);}else{JOptionPane.showMessageDialog(null,"除数不能为零","提醒", RMATION_MESSAGE);}end=true;}else if(e.getSource()==b_jia){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=0;opall=op1;flagop2=false;}else if(e.getSource()==b_jian){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=1;opall=op1;flagop2=false;}else if(e.getSource()==b_cheng){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=2;opall=op1;flagop2=false;}else if(e.getSource()==b_chu){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=3;opall=op1;flagop2=false;}else if(e.getSource()==b_dengyu){str = ta1.getText();if(flagop2==false){op2 = Double.parseDouble(str);flagop2=true;}switch(x){case 0 :opall=opall+op2;String s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 1 :opall=opall-op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 2 :opall=opall*op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 3 :opall=opall/op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;}end=true;}}public void addString(int num){String s=null;s=String.valueOf(num);//如果end==true;,那么屏幕清空if(end==true){ta1.setText("0");end=false;}if((ta1.getText()).equals("0")){ta1.setText(s);}else{if(ta1.getText().length()<21){str=ta1.getText()+s;ta1.setText(str);}}}public void mouseClicked(MouseEvent mec){if(mec.getModifiers()==mec.BUTTON3_MASK){popupmenu.show(ta1,mec.getX(),mec.getY());}}public void mousePressed(MouseEvent ms){}public void mouseReleased(MouseEvent md){}public void mouseEntered(MouseEvent ms){}public void mouseExited(MouseEvent mex){}public void mouseDragged(MouseEvent med){}}public class Calculator {public static void main(String[] args) {// TODO Auto-generated method stubCal jishuanji=new Cal("计算器");}}。

j2me计算器

j2me计算器

import javax.microedition.lcdui.Canvas;import mand;import mandListener;import javax.microedition.lcdui.Display;import javax.microedition.lcdui.Displayable;import javax.microedition.lcdui.Form;import javax.microedition.lcdui.Image;import javax.microedition.lcdui.ImageItem;import javax.microedition.lcdui.Item;import javax.microedition.lcdui.ItemStateListener;import javax.microedition.lcdui.TextField;import javax.microedition.midlet.MIDlet;import javax.microedition.midlet.MIDletStateChangeException;public class gaoji extends MIDlet implements CommandListener,ItemStateListener{ private Display display;private Form f;diji dj = new diji(null);private Command ExitCommand=new Command("EXIT",Command.EXIT,1);private Command OKCommand=new Command("OK",Command.OK,2);private Image szj;private ImageItem cc;public gaoji() { display = Display.getDisplay(this);}protected void destroyApp(boolean arg0) throws MIDletStateChangeException { // TODO Auto-generated method stub}protected void pauseApp() {display.setCurrent(null);f=null;}protected void startApp() throws MIDletStateChangeException {f=new Form("计算机程序");try{szj= Image.createImage("/songzhongji.png");cc = new ImageItem("欢迎进入计算界面~ ",szj,YOUT_CENTER,"无法显示!");f.append(cc);}catch (Exception e){System.out.println( e.toString());}f.addCommand(ExitCommand);f.addCommand(OKCommand);f.setCommandListener(this);f.setItemStateListener(this);display.setCurrent(f);}public void itemStateChanged(Item tx) {}public void commandAction(Command c, Displayable arg1) {if( c== OKCommand){display.setCurrent(dj);}if(c==ExitCommand){try {destroyApp(false);this.notifyDestroyed();}catch (Exception e) {}notifyDestroyed();}}}import javax.microedition.lcdui.*;public class diji extends Canvas implements CommandListener{private Command equ = new Command("equ", Command.BACK, 2);private Command cancel = new Command("cancel", Command.BACK, 1);private gaoji gj=null;public diji(gaoji g) {gj=g;this.addCommand(equ);this.addCommand(cancel);this.setCommandListener(this);setFullScreenMode(false);}String Str1 = "";String Str2;int ys,cc=0;int num1;int num2;int k;boolean clearFlag = true;String result1,result2,result3,result4;private int dx=30;private double ii,yunsuan;public int i=2;private int dy=30;private int rows=4;private int cols=3;String[][] num={{"1","2","3"},{"4","5","6"},{"7","8","9"},{"*","0","#"}} ;protected void paint(Graphics g) {g.setColor(0xffffff);g.fillRect(0, 0, 680, 208);g.setColor(0,0,0);g.drawRect(25, 15, 120, 16);g.drawString(Str1, 120, 15, 24);g.setColor(0,0,0);for(int i=0;i<=rows;i++)g.drawLine(40, i*dy+40, dx*cols+40, i*dy+40);for(int j=0;j<=cols;j++)g.drawLine(j*dy+40,40,j*dx+40,rows*dy+40);g.setColor(0,0,0);for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){g.setColor(0,0,0);g.drawString(num[i][j], j*dx+45, (i+1)*dy+40, Graphics.BOTTOM|Graphics.LEFT);}}if(num1==-13&ys==1){g.drawString("+",i,40,Graphics.TOP|Graphics.HCENTER);i=i+6;g.setColor(100,100,100);}if(num1==-13&ys==2){g.drawString("-",i,40,Graphics.TOP|Graphics.HCENTER);i=i+6;g.setColor(100,100,100);}if(num1==-13&ys==3){g.drawString("*",i,40,Graphics.TOP|Graphics.HCENTER);i=i+6;g.setColor(100,100,100);}if(num1==-13&ys==0){g.drawString("/",i,40,Graphics.TOP|Graphics.HCENTER);i=i+6;g.setColor(100,100,100);}if(cc==1){if(ys==11){Str1=result1;}if(ys==12){Str1=result2;}if(ys==13){Str1=result3;}if(ys==10){Str1=result4;}}}protected void keyPressed(int keycode){num1=keycode-48;if(num1>=0&&num1<=9){Str2=""+num1;Str1=Str1+Str2;ii=Double.parseDouble(Str1);clearFlag = true;}if(num1==-6){Str1=Str1+".";ii=Double.parseDouble(Str1);clearFlag = true;}if(num1==-13){k++;ys=k%4;yunsuan=ii;Str1="";Str2="";}result1=yunsuan+ii+"";result2=yunsuan-ii+"";result3=yunsuan*ii+"";result4=yunsuan/ii+"";this.repaint();}public void commandAction(Command c, Displayable d) { if( c== cancel){ this.repaint();clearFlag = true;Str1="";}if( c== equ){ cc=1;this.repaint();ys=ys+10;}}}。

j2me 代码 天气预报

j2me 代码 天气预报

view plaincopy to clipboardprint?01.package googleweather;02.03.import java.io.ByteArrayOutputStream;04.import java.io.DataInputStream;05.import java.io.IOException;06.import java.io.InputStream;07.import java.io.InputStreamReader;08.09.import javax.microedition.io.Connector;10.import javax.microedition.io.HttpConnection;11.import javax.microedition.lcdui.CustomItem;12.import javax.microedition.lcdui.Display;13.import javax.microedition.lcdui.Form;14.import javax.microedition.lcdui.Graphics;15.import javax.microedition.lcdui.Image;16.import javax.microedition.midlet.MIDlet;17.import javax.microedition.midlet.MIDletStateChangeException;18.19.import org.kxml2.io.KXmlParser;20.import org.xmlpull.v1.XmlPullParserException;21.22.public class GoogleWeather extends MIDlet {23. InputStream is;24. Display dis;25. Form f;26. int width ;27. String city ;28. String forecast_date;29. public GoogleWeather() {30. dis = Display.getDisplay(this);31.32. }33.34. protected void destroyApp(boolean arg0) throws MIDletStateChangeException {35. // TODO Auto-generated method stub36.37. }38.39. protected void pauseApp() {40. // TODO Auto-generated method stub41.42. }43.44. protected void startApp() throws MIDletStateChangeException {45. f = new Form("天气预报");46. width = f.getWidth();47. dis.setCurrent(f);48. getIS() ;49. if (is == null) f.append("is == null");50. parse();51. }52.53. public boolean getIS() {54. String url = "/ig/api?weather=Shanghai";55. HttpConnection hcon = null;56. boolean ret = false;57. try {58. hcon = (HttpConnection) Connector.open(url);59. String contentType = hcon.getHeaderField("Content-Type"); // 这里用来过滤移动资费页面60. if (contentType != null61. && contentType.indexOf("text/vnd.wap.wml") != -1) {62. hcon = null;63. hcon = (HttpConnection) Connector.open(url);64. }65. is = new DataInputStream(hcon.openInputStream());66. ret = true;67. } catch (Exception e) {68. ret = false;69. e.printStackTrace();70. }71. return ret;72. }73.74. public boolean parse() {75. KXmlParser parser;76. parser = new KXmlParser();77. boolean ret = false;78. try {79. parser.setInput(new InputStreamReader(is));80. xml_api_reply(parser);81.82. } catch (Exception e) {83. e.printStackTrace();84. }85. try {86. is.close();87. } catch (IOException e) {88. e.printStackTrace();89. }90. return ret;91. }92.93. private void xml_api_reply(KXmlParser parser) {94. try {95.96. parser.nextT ag();97. parser.require(KXmlParser.START_TAG, null, "xml_api_reply");98. parser.nextT ag();99. parser.require(KXmlParser.START_TAG, null, "weather");100. parser.nextT ag();101. forecast_information(parser);102. parser.nextT ag();103. current_conditions(parser);104. parser.nextT ag();105. forecast_conditions(parser);106. parser.nextT ag();107. forecast_conditions(parser);108. parser.nextT ag();109. forecast_conditions(parser);110. parser.nextT ag();111. forecast_conditions(parser);112. parser.nextT ag();113. parser.require(KXmlParser.END_TAG, null, "weather");114. parser.nextT ag();115. parser.require(KXmlParser.END_TAG, null, "xml_api_reply");116. } catch (XmlPullParserException e) {117. f.append("11");118. } catch (IOException e) {119. f.append("12");120. }121. }122.123. private void current_conditions(KXmlParser parser) throws XmlPullParserException, IOException {124.125. String condition,temp_f,temp_c ,humidity ,icon,wind_condition ;126. parser.require(KXmlParser.START_TAG, null, "current_conditions");127. parser.nextT ag();128. parser.require(KXmlParser.START_TAG, null, "condition");129. condition = parser.getAttributeValue(0);130. parser.nextT ag();131. parser.require(KXmlParser.END_TAG, null, "condition");132.133. parser.nextT ag();134. parser.require(KXmlParser.START_TAG, null, "temp_f");135. temp_f = parser.getAttributeValue(0);136. parser.nextT ag();137. parser.require(KXmlParser.END_TAG, null, "temp_f");138.139. parser.nextT ag();140. parser.require(KXmlParser.START_TAG, null, "temp_c");141. temp_c = parser.getAttributeValue(0);142. parser.nextT ag();143. parser.require(KXmlParser.END_TAG, null, "temp_c");144. parser.nextT ag();145. parser.require(KXmlParser.START_TAG, null, "humidity");146. humidity = parser.getAttributeValue(0);147. parser.nextT ag();148. parser.require(KXmlParser.END_TAG, null, "humidity");149. parser.nextT ag();150. parser.require(KXmlParser.START_TAG, null, "icon");151. icon = parser.getAttributeValue(0);152. parser.nextT ag();153. parser.require(KXmlParser.END_TAG, null, "icon");154. parser.nextT ag();155. parser.require(KXmlParser.START_TAG, null, "wind_condition");156. wind_condition = parser.getAttributeValue(0);157. parser.nextT ag();158. parser.require(KXmlParser.END_TAG, null, "wind_condition");159. parser.nextT ag();160.161.162. System.out.println(condition);163. System.out.println(temp_f);164. System.out.println(temp_c);165. System.out.println(humidity);166. System.out.println(icon);167. System.out.println(wind_condition);168.169. icon = "" + icon ;170.171. CurrentWeatherItem cwi = new CurrentWeatherItem(temp_c , city , forecast_date, loadHttpFile(icon));172. f.append(cwi);173. parser.require(KXmlParser.END_TAG, null, "current_conditions");174.175. }176.177. private Image loadHttpFile(String url) throws IOException {178.179. System.out.println(url);180. byte[] byteBuffer = null;181. HttpConnection hc = (HttpConnection) Connector.open(url);182. String contentType = hc.getHeaderField("Content-Type"); // 这里用来过滤移动资费页面183. if (contentType != null184. && contentType.indexOf("text/vnd.wap.wml") != -1) {185. hc = null;186. hc = (HttpConnection) Connector.open(url);187. }188. int code = hc.getResponseCode();189. if (code == 200) {190. try {191. InputStream is = hc.openInputStream();192. try {193. int len = (int) hc.getLength();194. if (len > 0) {195. byteBuffer = new byte[len];196. int done = 0;197. while (done < len) {198. done += is.read(byteBuffer, done, len - done);199. }200. } else {201. ByteArrayOutputStream bos = new ByteArrayOutputStream(); 202. byte[] buffer = new byte[512];203. int count;204. while ((count = is.read(buffer)) >= 0) {205. bos.write(buffer, 0, count);206. }207. byteBuffer = bos.toByteArray();208. }209. } finally {210. is.close();211. }212. } finally {213. hc.close();214. }215. }216. return Image.createImage(byteBuffer, 0, byteBuffer.length);217.218. }219.220. private void forecast_information(KXmlParser parser) throws XmlPullParserException, IOException {221. String city,postal_code,latitude_e6,longitude_e6,forecast_date,current_date_time,unit_system; 222. parser.require(KXmlParser.START_TAG, null, "forecast_information");223. parser.nextT ag();224. parser.require(KXmlParser.START_TAG, null, "city");225. city = parser.getAttributeValue(0);226. parser.nextT ag();227. parser.require(KXmlParser.END_TAG, null, "city");228. parser.nextT ag();229. parser.require(KXmlParser.START_TAG, null, "postal_code");230. postal_code = parser.getAttributeValue(0);231. parser.nextT ag();232. parser.require(KXmlParser.END_TAG, null, "postal_code");233. parser.nextT ag();234. parser.require(KXmlParser.START_TAG, null, "latitude_e6");235. latitude_e6 = parser.getAttributeValue(0);236. parser.nextT ag();237. parser.require(KXmlParser.END_TAG, null, "latitude_e6");238. parser.nextT ag();239. parser.require(KXmlParser.START_TAG, null, "longitude_e6");240. longitude_e6 = parser.getAttributeValue(0);241. parser.nextT ag();242. parser.require(KXmlParser.END_TAG, null, "longitude_e6");243. parser.nextT ag();244. parser.require(KXmlParser.START_TAG, null, "forecast_date");245. forecast_date = parser.getAttributeValue(0);246. parser.nextT ag();247. parser.require(KXmlParser.END_TAG, null, "forecast_date");248. parser.nextT ag();249. parser.require(KXmlParser.START_TAG, null, "current_date_time");250. current_date_time = parser.getAttributeValue(0);251. parser.nextT ag();252. parser.require(KXmlParser.END_TAG, null, "current_date_time");253. parser.nextT ag();254. parser.require(KXmlParser.START_TAG, null, "unit_system");255. unit_system = parser.getAttributeValue(0);256. parser.nextT ag();257. parser.require(KXmlParser.END_TAG, null, "unit_system");258. parser.nextT ag();259.260. System.out.println(city);261. System.out.println(postal_code);262. System.out.println(latitude_e6);263. System.out.println(longitude_e6);264. System.out.println(forecast_date);265. System.out.println(current_date_time);266. System.out.println(unit_system);267.268. this.city = city ;269. this.forecast_date = forecast_date ;270. parser.require(KXmlParser.END_TAG, null, "forecast_information");271.272. }273.274. private void forecast_conditions(KXmlParser parser) throws XmlPullParserException, IOException {275.276. String day_of_week,low,high,icon ,condition ;277. parser.require(KXmlParser.START_TAG, null, "forecast_conditions");278. parser.nextT ag();279. parser.require(KXmlParser.START_TAG, null, "day_of_week");280. day_of_week = parser.getAttributeValue(0);281. parser.nextT ag();282. parser.require(KXmlParser.END_TAG, null, "day_of_week");283.284. parser.nextT ag();285. parser.require(KXmlParser.START_TAG, null, "low");286. low = parser.getAttributeValue(0);287. parser.nextT ag();288. parser.require(KXmlParser.END_TAG, null, "low");289.290. parser.nextT ag();291. parser.require(KXmlParser.START_TAG, null, "high");292. high = parser.getAttributeValue(0);293. parser.nextT ag();294. parser.require(KXmlParser.END_TAG, null, "high");295. parser.nextT ag();296. parser.require(KXmlParser.START_TAG, null, "icon");297. icon = parser.getAttributeValue(0);298. parser.nextT ag();299. parser.require(KXmlParser.END_TAG, null, "icon");300. parser.nextT ag();301. parser.require(KXmlParser.START_TAG, null, "condition");302. condition = parser.getAttributeValue(0);303. parser.nextT ag();304. parser.require(KXmlParser.END_TAG, null, "condition");305. parser.nextT ag();306.307. System.out.println(day_of_week);308. System.out.println(low);309. System.out.println(high);310. System.out.println(icon);311. System.out.println(condition);312. icon = "" + icon ;313.314. if(day_of_week.equalsIgnoreCase("mon")) day_of_week = "周一" ;315. else if(day_of_week.equalsIgnoreCase("tue")) day_of_week = "周二";316. else if(day_of_week.equalsIgnoreCase("wed")) day_of_week = "周三";317. else if(day_of_week.equalsIgnoreCase("thu")) day_of_week = "周四";318. else if(day_of_week.equalsIgnoreCase("fri")) day_of_week = "周五";319. else if(day_of_week.equalsIgnoreCase("sat")) day_of_week = "周六";320. else day_of_week = "周日";321. low = String.valueOf((Integer.parseInt(low) - 32) * 5 / 9);322. high = String.valueOf((Integer.parseInt(high) - 32) * 5 / 9);323.324. ForecastWeatherItem fwi = new ForecastWeatherItem(day_of_week, low , high , loadHttpFile(icon));325. f.append(fwi);326. parser.require(KXmlParser.END_TAG, null, "forecast_conditions");327. }328.329. public class CurrentWeatherItem extends CustomItem{330.331. String temp ;332. String city ;333. String forecast_date;334. Image icon;335. protected CurrentWeatherItem(String temp , String city ,String forecast_date,Image icon ) {336. super(forecast_date);337. this.temp = temp ;338. this.city = city;339. this.forecast_date = forecast_date;340. this.icon = icon;341. }342.343. protected int getMinContentHeight() {344. // TODO Auto-generated method stub345. return 40;346. }347.348. protected int getMinContentWidth() {349. // TODO Auto-generated method stub350. return width;351. }352.353. protected int getPrefContentHeight(int arg0) {354. // TODO Auto-generated method stub355. return 40;356. }357.358. protected int getPrefContentWidth(int arg0) {359. // TODO Auto-generated method stub360. return width;361. }362.363. protected void paint(Graphics g, int arg1, int arg2) {364. g.setColor(0x9accff);365. g.fillRect(0, 0, width, 40);366. g.drawImage(this.icon, 20, 20, Graphics.HCENTER | Graphics.VCENTER); 367. g.setColor(0x000000);368. g.drawString("当前气温:" , 50, 10, 0);369. g.drawString(temp + "℃" , 100, 10, 0);370. }371. }372.373. public class ForecastWeatherItem extends CustomItem{374.375. String day_of_week;376. String low;377. String high ;378. Image icon;379. protected ForecastWeatherItem(String day_of_week, String low, String high , Image icon) {380. super(null);381. this.day_of_week = day_of_week;382. this.low = low;383. this.high = high ;384. this.icon = icon ;385. }386.387. protected int getMinContentHeight() {388. // TODO Auto-generated method stub389. return 40;390. }391.392. protected int getMinContentWidth() {393. // TODO Auto-generated method stub394. return width;395. }396.397. protected int getPrefContentHeight(int arg0) {398. // TODO Auto-generated method stub399. return 40;400. }401.402. protected int getPrefContentWidth(int arg0) {403. // TODO Auto-generated method stub404. return width;405. }406.407. protected void paint(Graphics g, int arg1, int arg2) {408. g.setColor(0x66cbff);409. g.fillRect(0, 0, width, 40);410. g.drawImage(this.icon, 20, 20, Graphics.HCENTER | Graphics.VCENTER); 411. g.setColor(0x000000);412. g.drawString(day_of_week , 50, 10, 0);413. g.drawString(low + "℃/" + high + "℃", 100, 10, 0);414. }415. }416.}package googleweather;import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import javax.microedition.io.Connector;import javax.microedition.io.HttpConnection;import javax.microedition.lcdui.CustomItem;import javax.microedition.lcdui.Display;import javax.microedition.lcdui.Form;import javax.microedition.lcdui.Graphics;import javax.microedition.lcdui.Image;import javax.microedition.midlet.MIDlet;import javax.microedition.midlet.MIDletStateChangeException;import org.kxml2.io.KXmlParser;import org.xmlpull.v1.XmlPullParserException;public class GoogleWeather extends MIDlet {InputStream is;Display dis;Form f;int width ;String city ;String forecast_date;public GoogleWeather() {dis = Display.getDisplay(this);}protected void destroyApp(boolean arg0) throws MIDletStateChangeException { // TODO Auto-generated method stub}protected void pauseApp() {// TODO Auto-generated method stub}protected void startApp() throws MIDletStateChangeException {f = new Form("天气预报");width = f.getWidth();dis.setCurrent(f);getIS() ;if (is == null) f.append("is == null");parse();}public boolean getIS() {String url = "/ig/api?weather=Shanghai";HttpConnection hcon = null;boolean ret = false;try {hcon = (HttpConnection) Connector.open(url);String contentType = hcon.getHeaderField("Content-Type"); // 这里用来过滤移动资费页面if (contentType != null&& contentType.indexOf("text/vnd.wap.wml") != -1) {hcon = null;hcon = (HttpConnection) Connector.open(url);}is = new DataInputStream(hcon.openInputStream());ret = true;} catch (Exception e) {ret = false;e.printStackTrace();}return ret;}public boolean parse() {KXmlParser parser;parser = new KXmlParser();boolean ret = false;try {parser.setInput(new InputStreamReader(is));xml_api_reply(parser);} catch (Exception e) {e.printStackTrace();}try {is.close();} catch (IOException e) {e.printStackTrace();}return ret;}private void xml_api_reply(KXmlParser parser) {try {parser.nextTag();parser.require(KXmlParser.START_TAG, null, "xml_api_reply");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "weather");parser.nextTag();forecast_information(parser);parser.nextTag();current_conditions(parser);parser.nextTag();forecast_conditions(parser);parser.nextTag();forecast_conditions(parser);parser.nextTag();forecast_conditions(parser);parser.nextTag();forecast_conditions(parser);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "weather");parser.nextTag();parser.require(KXmlParser.END_TAG, null, "xml_api_reply");} catch (XmlPullParserException e) {f.append("11");} catch (IOException e) {f.append("12");}}private void current_conditions(KXmlParser parser) throws XmlPullParserException, IOException {String condition,temp_f,temp_c ,humidity ,icon,wind_condition ;parser.require(KXmlParser.START_TAG, null, "current_conditions");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "condition");condition = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "condition");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "temp_f");temp_f = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "temp_f");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "temp_c");temp_c = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "temp_c");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "humidity");humidity = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "humidity");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "icon");icon = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "icon");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "wind_condition");wind_condition = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "wind_condition");parser.nextTag();System.out.println(condition);System.out.println(temp_f);System.out.println(temp_c);System.out.println(humidity);System.out.println(icon);System.out.println(wind_condition);icon = "" + icon ;CurrentWeatherItem cwi = new CurrentWeatherItem(temp_c , city , forecast_date, loadHttpFile(icon));f.append(cwi);parser.require(KXmlParser.END_TAG, null, "current_conditions");}private Image loadHttpFile(String url) throws IOException {System.out.println(url);byte[] byteBuffer = null;HttpConnection hc = (HttpConnection) Connector.open(url);String contentType = hc.getHeaderField("Content-Type"); // 这里用来过滤移动资费页面if (contentType != null&& contentType.indexOf("text/vnd.wap.wml") != -1) {hc = null;hc = (HttpConnection) Connector.open(url);}int code = hc.getResponseCode();if (code == 200) {try {InputStream is = hc.openInputStream();try {int len = (int) hc.getLength();if (len > 0) {byteBuffer = new byte[len];int done = 0;while (done < len) {done += is.read(byteBuffer, done, len - done);}} else {ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] buffer = new byte[512];int count;while ((count = is.read(buffer)) >= 0) {bos.write(buffer, 0, count);}byteBuffer = bos.toByteArray();}} finally {is.close();}} finally {hc.close();}}return Image.createImage(byteBuffer, 0, byteBuffer.length);}private void forecast_information(KXmlParser parser) throws XmlPullParserException, IOException {Stringcity,postal_code,latitude_e6,longitude_e6,forecast_date,current_date_time,unit_system;parser.require(KXmlParser.START_TAG, null, "forecast_information");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "city");city = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "city");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "postal_code"); postal_code = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "postal_code"); parser.nextTag();parser.require(KXmlParser.START_TAG, null, "latitude_e6"); latitude_e6 = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "latitude_e6"); parser.nextTag();parser.require(KXmlParser.START_TAG, null, "longitude_e6"); longitude_e6 = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "longitude_e6"); parser.nextTag();parser.require(KXmlParser.START_TAG, null, "forecast_date"); forecast_date = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "forecast_date"); parser.nextTag();parser.require(KXmlParser.START_TAG, null, "current_date_time"); current_date_time = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "current_date_time"); parser.nextTag();parser.require(KXmlParser.START_TAG, null, "unit_system");unit_system = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "unit_system"); parser.nextTag();System.out.println(city);System.out.println(postal_code);System.out.println(latitude_e6);System.out.println(longitude_e6);System.out.println(forecast_date);System.out.println(current_date_time);System.out.println(unit_system);this.city = city ;this.forecast_date = forecast_date ;parser.require(KXmlParser.END_TAG, null, "forecast_information");}private void forecast_conditions(KXmlParser parser) throws XmlPullParserException, IOException {String day_of_week,low,high,icon ,condition ;parser.require(KXmlParser.START_TAG, null, "forecast_conditions");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "day_of_week");day_of_week = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "day_of_week");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "low");low = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "low");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "high");high = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "high");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "icon");icon = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "icon");parser.nextTag();parser.require(KXmlParser.START_TAG, null, "condition");condition = parser.getAttributeValue(0);parser.nextTag();parser.require(KXmlParser.END_TAG, null, "condition");parser.nextTag();System.out.println(day_of_week);System.out.println(low);System.out.println(high);System.out.println(icon);System.out.println(condition);icon = "" + icon ;if(day_of_week.equalsIgnoreCase("mon")) day_of_week = "周一" ;else if(day_of_week.equalsIgnoreCase("tue")) day_of_week = "周二";else if(day_of_week.equalsIgnoreCase("wed")) day_of_week = "周三";else if(day_of_week.equalsIgnoreCase("thu")) day_of_week = "周四";else if(day_of_week.equalsIgnoreCase("fri")) day_of_week = "周五";else if(day_of_week.equalsIgnoreCase("sat")) day_of_week = "周六";else day_of_week = "周日";low = String.valueOf((Integer.parseInt(low) - 32) * 5 / 9);high = String.valueOf((Integer.parseInt(high) - 32) * 5 / 9);ForecastWeatherItem fwi = new ForecastWeatherItem(day_of_week, low , high , loadHttpFile(icon));f.append(fwi);parser.require(KXmlParser.END_TAG, null, "forecast_conditions");}public class CurrentWeatherItem extends CustomItem{String temp ;String city ;String forecast_date;Image icon;protected CurrentWeatherItem(String temp , String city ,String forecast_date,Image icon ) {super(forecast_date);this.temp = temp ;this.city = city;this.forecast_date = forecast_date;this.icon = icon;}protected int getMinContentHeight() {// TODO Auto-generated method stubreturn 40;}protected int getMinContentWidth() {// TODO Auto-generated method stubreturn width;}protected int getPrefContentHeight(int arg0) {// TODO Auto-generated method stubreturn 40;}protected int getPrefContentWidth(int arg0) {// TODO Auto-generated method stubreturn width;}protected void paint(Graphics g, int arg1, int arg2) {g.setColor(0x9accff);g.fillRect(0, 0, width, 40);g.drawImage(this.icon, 20, 20, Graphics.HCENTER | Graphics.VCENTER);g.setColor(0x000000);g.drawString("当前气温:" , 50, 10, 0);g.drawString(temp + "℃" , 100, 10, 0);}}public class ForecastWeatherItem extends CustomItem{String day_of_week;String low;String high ;Image icon;protected ForecastWeatherItem(String day_of_week, String low, String high , Image icon) {super(null);this.day_of_week = day_of_week;this.low = low;this.high = high ;this.icon = icon ;}protected int getMinContentHeight() {// TODO Auto-generated method stubreturn 40;}protected int getMinContentWidth() {// TODO Auto-generated method stubreturn width;}protected int getPrefContentHeight(int arg0) {// TODO Auto-generated method stubreturn 40;。

毕业设计-程序清单

毕业设计-程序清单

北京联合大学毕业设计(论文)程序清单题目:手机计算器开发(J2ME) 专业:通信工程指导教师: (关博深) / 联系(张宁)学院:信息学院学号:2007080304217班级:200708030402姓名:崔元宏一、程序清单CalcForm.javapackage calc.pkg;import javax.microedition.lcdui.*;import java.util.*;import javax.microedition.midlet.MIDlet;import com.sun.perseus.model.Symbol;/*** 该类描述了计算器。

* 实现了计算器的界面,及加、减、乘、除等计算功能。

*/public class CalcForm extends Form implements CalcKeyboardListener { // static CalcScreen showArea; //计算器的显示区public CalcKeyboard ckeyboard; //计算器键盘private boolean hasNewOperand = false; //有新的操作数private boolean numInputing = false;public double acc = 0.0; //累加器public double m = 0.0;private String operator = ""; //运算符private double operand = 0.0; //操作数public StringItem si1;public CalcForm() {super("手机计算器by:崔元宏");ckeyboard = new CalcKeyboard(5, 7); //创建计算器的键盘si1 = new StringItem(" ","");showArea = new CalcScreen(); //创建计算器的显示区对象ckeyboard.setCalcKeyboardListener(this); ////布局showArea.setLayout(YOUT_2|YOUT_CENTER|YOUT_NEWLI NE_AFTER);append(showArea);si1.setLayout(YOUT_RIGHT);append(si1);ckeyboard.setLayout(YOUT_2|YOUT_CENTER);append(ckeyboard);append(new Spacer(this.getWidth(), 6));reset();}//按钮单击事件处理方法//如果设备支持触摸屏功能,当用户使用笔在按钮上单击后,//注册在键盘上的监视器将调用下面的方法,对单击事件进行处理。

JAVA编写的计算器源代码(word文档良心出品)

JAVA编写的计算器源代码(word文档良心出品)

package jsq;import java.awt.Color;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.UIManager;public class Test implements ActionListener {/****/JFrame f = new JFrame();JTextField tf = new JTextField("0.");JMenuBar bar=new JMenuBar();JMenu menuEdit=new JMenu("编辑(E)");JMenu menuView=new JMenu("查看(V)");JMenu menuHelp=new JMenu("帮助(H)");JMenuItem menuEditCopy=new JMenuItem("复制(C)");JMenuItem menuEditPaste=new JMenuItem("粘贴(V)");JMenuItem menuHelpAbout = new JMenuItem("关于计算器(A)");JPanel panel0 = new JPanel();JPanel panel2 = new JPanel();JPanel panel = new JPanel();JPanel panel3 = new JPanel();JPanel panel4 = new JPanel();JPanel panel5 = new JPanel();JButton btBk = new JButton(" Backspace"); JButton btCe = new JButton("Ce");JButton btCl = new JButton("C");JButton bt7 = new JButton("7");JButton bt8 = new JButton("8");JButton bt9 = new JButton("9");JButton btDiv = new JButton("/");JButton btSqrt = new JButton("sqrt");JButton bt4 = new JButton("4");JButton bt5 = new JButton("5");JButton bt6 = new JButton("6");JButton btMult = new JButton("*"); JButton btMol = new JButton(" % ");JButton bt1 = new JButton("1");JButton bt2 = new JButton("2");JButton bt3 = new JButton("3");JButton btMinu = new JButton("-"); JButton btCoun = new JButton(" 1/x");JButton bt0 = new JButton("0");JButton btPoint = new JButton("."); JButton btEqual = new JButton("="); JButton btAdd = new JButton("+");JButton btSign = new JButton(" +/-");/***@param args*/public void init(){f.add(panel0);f.add(tf,"North");f.setJMenuBar(bar);bar.add(menuEdit);bar.add(menuView);bar.add(menuHelp);menuEdit.add(menuEditCopy);menuEdit.add(menuEditPaste);menuHelp.add(menuHelpAbout);tf.setEditable(false);//不可编辑tf.setHorizontalAlignment(JTextField.RIGHT);//从右侧输入数据panel0.add(panel2);panel0.add(panel);panel0.add(panel3);panel0.add(panel4);panel0.add(panel5);panel2.setLayout(new GridLayout(1,4));panel2.add(btBk);panel2.add(btCe);panel2.add(btCl);panel.setLayout(new GridLayout(1,5));panel.add(bt7);panel.add(bt8);panel.add(bt9);panel.add(btDiv);panel.add(btSqrt);//根号panel3.setLayout(new GridLayout(1,5));panel3.add(bt4);panel3.add(bt5);panel3.add(bt6);panel3.add(btMult);panel3.add(btMol);//百分号panel4.setLayout(new GridLayout(1,5));panel4.add(bt1);panel4.add(bt2);panel4.add(bt3);panel4.add(btMinu);panel4.add(btCoun);//倒数panel5.setLayout(new GridLayout(1,5));panel5.add(bt0);panel5.add(btPoint);panel5.add(btAdd);panel5.add(btEqual);panel5.add(btSign);//正负符号btBk.setForeground(new Color(255, 0, 0)); btCe.setForeground(new Color(255, 0, 0)); btCl.setForeground(new Color(255, 0, 0)); btAdd.setForeground(new Color(255, 0, 0)); btMult.setForeground(new Color(255, 0, 0)); btDiv.setForeground(new Color(255, 0, 0)); btMinu.setForeground(new Color(255, 0, 0)); btEqual.setForeground(new Color(255, 0, 0));bt0.setForeground(new Color(0,0,255));bt1.setForeground(new Color(0, 0, 255));bt2.setForeground(new Color(0,0,255));bt3.setForeground(new Color(0,0,255));bt4.setForeground(new Color(0,0,255));bt5.setForeground(new Color(0,0,255));bt6.setForeground(new Color(0,0,255));bt7.setForeground(new Color(0,0,255));bt8.setForeground(new Color(0,0,255));bt9.setForeground(new Color(0,0,255)); btSqrt.setForeground(new Color(0,0,255)); btMol.setForeground(new Color(0,0,255)); btCoun.setForeground(new Color(0,0,255)); btSign.setForeground(new Color(0,0,255));//注册监听bt1.addActionListener(this);bt2.addActionListener(this);bt3.addActionListener(this);bt4.addActionListener(this);bt5.addActionListener(this);bt6.addActionListener(this);bt7.addActionListener(this);bt8.addActionListener(this);bt9.addActionListener(this);bt0.addActionListener(this);btAdd.addActionListener(this);btMinu.addActionListener(this);btMult.addActionListener(this);btDiv.addActionListener(this);btEqual.addActionListener(this);btPoint.addActionListener(this);btSqrt.addActionListener(this);btMol.addActionListener(this);btCoun.addActionListener(this);btSign.addActionListener(this);btBk.addActionListener(this);btCe.addActionListener(this);btCl.addActionListener(this);menuEditCopy.addActionListener(this);menuEditPaste.addActionListener(this);menuHelpAbout.addActionListener(this);f.addWindowListener(new MyWinLis());f.setTitle("计算器");f.setSize(295,240);f.setResizable(false);//不能改变窗体大小f.setVisible(true);}String foreNum=null;String currOpr=null;String currNum=null;boolean i = true;String copy;//复制public void actionPerformed(ActionEvent e) {// TODO自动生成方法存根Object obj=e.getSource();//输入数字if(obj==bt1||obj==bt2||obj==bt3||obj==bt4||obj==bt5||obj==bt6||obj==bt7||obj== bt8||obj==bt9||obj==bt0){if(i==true)tf.setText(e.getActionCommand());elsetf.setText(tf.getText()+e.getActionCommand());i = false;}//小数点else if(obj==btPoint){if(i==false)tf.setText(tf.getText()+'.');}//实现开根号else if(obj==btSqrt){if(tf.getText().charAt(0)=='-'){tf.setText("函数输入无效");}elsetf.setText(Double.toString(ng.Math.sqrt(Double. parseDouble(tf.getText()))));i = true;}//实现倒数else if(obj==btCoun){if (tf.getText().charAt(0) == '0') {tf.setText("零不能求倒数");i = true;}else {String s = Double.toString(1 / Double.parseDouble(tf.getText()));foreNum = tf.getText();tf.setText(s);i = true;}}//实现+/-符号else if (obj == btSign) {boolean isNumber = true;String s = tf.getText();for (int m = 0; m< s.length(); m++)if (! (s.charAt(m) >= '0' && s.charAt(m) <='9' || s.charAt(m) =='.'||s.charAt(m) == '-')) {break;}if (isNumber == true) {//如果当前字符串首字母有-号,代表现在是个负数,再按下时,则将首符号去掉if (s.charAt(0) == '-') {tf.setText("");for (int m = 1; m< s.length(); m++) {char a = s.charAt(m);tf.setText(tf.getText() + a);}}//如果当前字符串第一个字符不是符号,则添加一个符号在首字母处elsetf.setText('-' + s);}}//实现%功能else if(obj==btMol){boolean isNumber = true;if(isNumber==true)tf.setText(String.valueOf(Double.parseDouble(tf.getText())/100));elsetf.setText("错误");}//实现符号运算else if(obj==btAdd||obj==btMinu||obj==btDiv||obj==btMult){if(i==false){currNum=tf.getText();if(currOpr=="+")tf.setText(String.valueOf(Double.parseDouble(foreNum)+Double.parseDouble(currN um)));else if(currOpr=="-")tf.setText(String.valueOf(Double.parseDouble(foreNum)-Double.parseDouble(currN um)));else if(currOpr=="*")tf.setText(String.valueOf(Double.parseDouble(foreNum)*Double.parseDouble(currN um)));else if(currOpr=="/"){if (Double.parseDouble(tf.getText()) == 0)tf.setText("除数不能为零");elsetf.setText(String.valueOf(Double.parseDouble(foreNum)/Double.parseDouble(currNum))) ;}}foreNum=tf.getText();tf.setText("");currOpr=e.getActionCommand();i = false;}//实现等号else if(obj==btEqual){currNum=tf.getText();if(currOpr=="+")tf.setText(String.valueOf(Double.parseDouble(foreNum)+Double.parseDouble(currN um)));else if(currOpr=="-")tf.setText(String.valueOf(Double.parseDouble(foreNum)-Double.parseDouble(currN um)));else if(currOpr=="*")tf.setText(String.valueOf(Double.parseDouble(foreNum)*Double.parseDouble(currN um)));else if(currOpr=="/"){if (Double.parseDouble(tf.getText()) == 0)tf.setText("除数不能为零");elsetf.setText(String.valueOf(Double.parseDouble(foreNum)/Double.parseDouble(currN um)));}currOpr=e.getActionCommand();i = true;}//实现Backspace功能else if(obj==btBk){String s = tf.getText();tf.setText("");for (int m = 0;m <s.length() - 1; m++) {char a = s.charAt(m);tf.setText(tf.getText() + a);i = true;}}//实现Ce功能else if (obj == btCe) {tf.setText("0.");}//实现C功能else if (obj == btCl) {foreNum=currNum="";tf.setText("0.");}//实现复制else if(obj==menuEditCopy){copy=tf.getText();}//实现粘贴else if (obj == menuEditPaste) {tf.setText(copy);}//实现帮助主题else if(obj == menuHelpAbout){ImageIcon icon = new ImageIcon("src//Icons//about1.jpg");JLabel label = new JLabel(icon);JOptionPane.showMessageDialog(f,label,"帮助主题",JOptionPane.PLAIN_MESSAGE);}}public static void main(String[] args) {// TODO自动生成方法存根try{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());//UIManager统一管理}catch(Exception e) {e.printStackTrace();}Test t = new Test();t.init();}}class MyWinLis implements WindowListener{public void windowActivated(WindowEvent arg0) {// TODO自动生成方法存根}public void windowClosed(WindowEvent arg0) { // TODO自动生成方法存根}public void windowClosing(WindowEvent arg0) { // TODO自动生成方法存根System.exit(0);}public void windowDeactivated(WindowEvent arg0) { // TODO自动生成方法存根}public void windowDeiconified(WindowEvent arg0) { // TODO自动生成方法存根}public void windowIconified(WindowEvent arg0) { // TODO自动生成方法存根}public void windowOpened(WindowEvent arg0) { // TODO自动生成方法存根}}。

Java科学计算器程序代码

Java科学计算器程序代码

计算器布局显示:功能举例:①13+20=33②-7*14=-98 :先输入7,再单击-/+将其变成负数,然后依次单击X号、14与=③7!=5040④s in30 ° =0.5 :先输入30,然后按下’〃按钮转换成角度值,再按下sin即可显示结果⑤s qrt(4)=2 :禾U用鼠标点击4后再点击sqrt按键即可显示结果⑥2* n =6.2832源程序如下:import java.awt.BorderLayout;import java.awt.Color;import java.awt.Dimension;import java.awt.Font;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.text.DecimalFormat;import javax.swing.BorderFactory;import javax.sw in g.Butt on Group;import javax.swing.JButton;import javax.swing.JCheckBoxMenuItem;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.JRadioButtonMenultem; import javax.swing.JTextField;editltem1new JMenultem("复制(C) Ctrl+C");public class Calucatorextends JFrame {private JTextField tf ;private JPa nel pan ell , pan el2 , pan el3 , pan el4 ; private JMenuBar myBar;private JMenu menu1, menu2 menu3private JMenultem editltem1 , editltem2 , help1 , help2 , help3;private JRadioButtonMenultem seeItem1 , seeItem2 ;//单选框 private JCheckBoxMenultem seeItem3 ; // 复选框 private Butt on Group bgb; private String back;private boolean IfResult = true , flag = false ; private String oper ="="; private double result = 0;private Num nu mAct ion Liste ner ; private DecimalFormat df; public Calucator(){super ("科学计算器”);//设置标题栏df = new DecimalFormat( "#.####" ); // 保留四位小数 this .setLayout( new BorderLayout(10, 5));new GridLayout(1, 3, 10, 10)); new GridLayout(5, 6, 5, 5)); new JPanel( new GridLayout(5, 1,5, 5)); new JPanel( new BorderLayout(5, 5));/** *菜单栏 */myBar = new JMe nuBar();menu 仁 new JMenu (” 编辑(E)"); menu2= new JMenu("查看(V)"); menu3= new JMenu("帮助(H)");*编辑栏 */pan el1 = new JPa nel( pan el2 = new JPa nel( 〃5行6列pan el3 = pan el4 = men u1.setF ont( menu2setF ont( new Font( new Font( "宋体",Font. "宋体",Font.PLAIM 12)); PLAIN 12)); menu 3setF ont( new Font("宋体 ”,Font.PLAIN 12));editltem2 = new JMenultem("粘贴(P) Ctrl+V"); editlteml .setFont( new Font("宋体",Font. PLAIN 12)); editltem2 .setFont( new Font("宋体",Font. PLAIN J12)); /***查看栏 */seeItem1 = new JRadioButtonMenultem("科学型(T)"); seeItem2 = new JRadioButtonMenultem("标准型(S)"); seeltem3 = new JCheckBoxMenultem("数字分组(I)");new Font("宋体",Font. PLAIN 12)); new Font("宋体",Font. PLAIN 12)); new Font("宋体",Font. PLAIN 12));*帮助栏 */help1 = new JMenultem("帮助主题(H)"); help2 = new JMenultem("关于计算器(A)");help1 .setFont( newFont("宋体”,Font. PLAIN J12)); help2 .setFont( newFont("宋体”,Font. PLAIN ,12)); bgb = new Butt on Group(); // 选项组 menu1.add( editltem1 ); menu1.add( editltem2 ); menu2add( seeltem1 ); menu2add( seeltem2 );menu2addSeparator(); // 添加一条分割线 menu2add( seeltem3 ); menu3add( help1 );menu3addSeparator(); // 添加一条分割线 menu3add( help2 ); myBar.add( menu1); myBar.add( menu 。

java教材源代码第13章 J2ME应用程序开发

java教材源代码第13章 J2ME应用程序开发

第13章J2ME应用程序开发在新创建的HelloWorld.java文件中输入如下代码。

//HelloWorld.javaimport javax.microedition.lcdui.*;import javax.microedition.midlet.MIDlet;public class HelloWorld extends MIDlet {Display display;public HelloWorld() {super();display = Display.getDisplay(this);}protected void startApp(){Form form = new Form("Hello World!");form.append("Welcome to J2ME world!");display.setCurrent(form);}protected void pauseApp() {}protected void destroyApp(boolean arg0){}}13.3.4 案例分析:MIDP应用程序实例本例的实现代码如下。

// DisplayMIDlet.java MIDlet应用程序实例import javax.microedition.lcdui.*;import javax.microedition.midlet.*;public class DisplayMIDlet extends MIDlet implements CommandListener { //Display管理Display display = null;//Form对象Form form = new Form("演示Display的使用");//创建命令按钮static final Command cmdOpenBackLight =new Command("打开背光灯", Command.ITEM,1);static final Command cmdStartVibrate =new Command("开始振动", Command.ITEM,1);static final Command cmdCloseBackLight =new Command("关闭背光灯", Command.ITEM,1);static final Command cmdStopVibrate =new Command("停止振动", Command.ITEM,1);static final Command cmdExit = new Command("退出", Command.STOP, 2);//构造函数public DisplayMIDlet() {// TODO 自动生成构造函数存根}protected void destroyApp(boolean arg0) throws MIDletStateChangeException { // TODO 自动生成方法存根notifyDestroyed();}protected void pauseApp() {// TODO 自动生成方法存根}protected void startApp() throws MIDletStateChangeException {// TODO 自动生成方法存根form.addCommand(cmdExit);form.addCommand(cmdOpenBackLight);form.addCommand(cmdCloseBackLight);form.addCommand(cmdStartVibrate);form.addCommand(cmdStopVibrate);form.setCommandListener(this);display = Display.getDisplay(this); //获得当前MIDlet的Display对象 display.setCurrent(form); //设置form对象为当前显示对象//显示是否支持彩色显示displayIsColor();//获取当前设备支持的最大颜色数displayNumberOfColors();//显示颜色常量的RGB值displayColorRGB();//显示当前设备能支持的Alpha级别displayAlphaLevel();}public void commandAction(Command arg0, Displayable arg1) {// TODO 自动生成方法存根String label = arg0.getLabel();if (label.equals("退出")) {try {destroyApp(true);} catch (MIDletStateChangeException e) {// TODO 自动生成 catch 块e.printStackTrace();}} else if(label.equals("打开背光灯")) {display.flashBacklight(40000);} else if(label.equals("关闭背光灯")) {display.flashBacklight(0);} else if(label.equals("开始振动")) {display.vibrate(40000);} else if(label.equals("停止振动")) {display.vibrate(0);}}/*** 获取当前设备支持的最大颜色数*/private void displayNumberOfColors() {int number = display.numColors();form.append("当前设备支持的颜色数:" + number);}/*** 显示是否支持彩色显示*/private void displayIsColor() {boolean color = display.isColor();form.append("当前设备是否支持彩色:" + color);}/*** 显示颜色常量的RGB值*/private void displayColorRGB() {String color;color = Integer.toHexString(display.getColor(Display.COLOR_BACKGROUND)).toUpperCase();form.append("背景颜色:" + color + "\n");color = Integer.toHexString(display.getColor(Display.COLOR_BORDER)).toUpperCase();form.append("边框颜色:" + color + "\n");color = Integer.toHexString(display.getColor(Display.COLOR_FOREGROUND)).toUpperCase();form.append("前景颜色:" + color + "\n");color = Integer.toHexString(display.getColor(Display.COLOR_HIGHLIGHTED_BACKGROUND)).toUpperCase(); form.append("高亮的背景颜色:" + color + "\n");color = Integer.toHexString(display.getColor(Display.COLOR_HIGHLIGHTED_BORDER)).toUpperCase();form.append("高亮的边框颜色:" + color + "\n");color = Integer.toHexString(display.getColor(Display.COLOR_HIGHLIGHTED_FOREGROUND)).toUpperCase();form.append("高亮的前景颜色:" + color + "\n");}/*** 显示当前设备能支持的Alpha级别*/private void displayAlphaLevel() {int level = display.numAlphaLevels();form.append("当前设备能支持的Alpha级别:" + level);}}13.4.5 案例分析:手机小游戏应用程序实例本例的实现代码如下。

J2ME手机编程心得

J2ME手机编程心得

J2ME手机编程心得(一)自学J2ME也有一段时间了,总觉得应该把自己学习的心得与收获写出来,一直没有时间,不过不管有没有时间还是要抽出时间总结一下的了,一点点的写吧!a.开发工具想要做J2ME开发,当然需要选择合适的开发测试工具,这里我选择的是SUN的WTK2.2版本,开发的集成IDE采用JBuilder2005。

WTK2.2可以在SUN公司的网站下载(/j2me/index.jsp),JBuilder2005嘛,网上搜索一下也有很多破解版下载的地方(没办法,咱买不起正版)。

下载以后进行安装,安装过程十分简单这里也不过多描述。

还有如果是想要开发游戏之类的,可能还需要一些图形处理工具,图形处理工具可以选择Macromedia Fireworks 8.0,一般的图形处理都能顺利的完成。

如果是开发RPG游戏,可能还需要一个地图编辑器来制作地图,如果你有时间或者有精力完全可以自己开发一个合适的地图编辑器,不过为了免得麻烦,能在网上找到的资源还是利用一下吧,这里推荐一款开源的地图编辑器,"Tile Studio",使用起来还算比较方便,可以到/下载,具体的使用方法在以后的文章中再做具体描述,这里不多说。

b.开发环境配置安装完毕以后,接下来要做的就是配置开发环境,JBuilder2005本来是带了WTK2.1的,不过我们还是用2.2的版本好了,首先打开JBuilder2005,打开Project -> Default Project Properties窗口,如下图:再点击JDK边上的"..."按钮,打开选择JDK的窗口,如下图:然后点击"New..."按钮,打开配置JDK的窗口:这里是选择JDK的目录的地方,点击"..."按钮,会出现选择JDK的Home文件夹的窗口,选择你装WTK的位置,比如E:\WTK2.2,点击"确定",如果WTK装的没问题,Name for this JDK的文本框会自动变成"J2ME Wireless Toolkit 2.2",这就代表JBuilder已经自动找到了WTK2.2,然后点击"OK",就新添加了一个JDK,然后在上一步选择JDK的窗口选择"J2ME Wireless Toolkit 2.2",就完成了WTK2.2在JBuilder里面的配置过程。

J2ME版本的GIF解码器源代码

J2ME版本的GIF解码器源代码
protected int transIndex; // transparent color index
protected static final int MaxStackSize = 4096;
// max decoder pixel stack size
// LZW decoder working arrays
* BufferedImage frame = d.getFrame(i); // frame i
* int t = d.getDelay(i); // display duration of frame in milliseconds
* // do something with frame
// fill in starting image contents based on last image's dispose code
if (lastDispose > 0) {
if (lastDispose == 3) {
// use image before last
protected int width; // full image width
protected int height; // full image height
protected boolean gctFlag; // global color table used
protected int lastDispose = 0;
protected boolean transparency = false; // use transparent color
protected int delay = 0; // delay in milliseconds

计算器的Java源代码

计算器的Java源代码

计算器程序的源代码import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Calculator extends Frame implements ActionListener, WindowListener{private Container container;private GridBagLayout layout;private GridBagConstraints constraints;private JTextField displayField; //计算结果显示区private String lastCommand; //保存+,-,*,/,=命令0private double result; //保存计算结果private boolean start; //判断是否为数字的开始private JMenuBar menubar;private JMenuItem m_exit,m2_ejz,m2_bjz;private Dialog dialog;private Label label_dialog;private JButton button_sqrt,button_plusminus,button_CE,button_cancel,button_1,button_2,button_3,button_4,button_5,button_6,button_7,button_8,button_9,button_0, button_plus,button_minus,button_multiply,button_divide,button_point,button_equal,button_log,button_tan,button_cos,button_sin,button_exp;public Calculator() //构造方法设置布局、为按钮注册事件监听器{super("Calculator");this.setLocation(240,200);this.setSize(350,300);this.setResizable(true);this.setLayout(new GridLayout(7,1));this.addmyMenu(); //调用成员方法添加菜单displayField=new JTextField(30);this.add(displayField);displayField.setEditable(true);start=true;result=0;lastCommand = "=";JPanel panel0=new JPanel();panel0.setLayout(new GridLayout(1,4,4,4));JPanel panel1=new JPanel();panel1.setLayout(new GridLayout(1,5,4,4));this.add(panel1);button_sqrt=new JButton("sqrt");button_plusminus=new JButton("+/-");button_exp=new JButton("exp");button_CE=new JButton("C");button_cancel=new JButton("CE");JPanel panel2=new JPanel();panel2.setLayout(new GridLayout(1,5,4,4));this.add(panel2);button_7=new JButton("7");button_8=new JButton("8");button_9=new JButton("9");button_log=new JButton("log");button_divide=new JButton("/");JPanel panel3=new JPanel();panel3.setLayout(new GridLayout(1,5,4,4));this.add(panel3);button_4=new JButton("4");button_5=new JButton("5");button_6=new JButton("6");button_tan=new JButton("tan");button_multiply=new JButton("*");JPanel panel4=new JPanel();panel4.setLayout(new GridLayout(1,5,4,4));this.add(panel4);button_1=new JButton("1");button_2=new JButton("2");button_3=new JButton("3");button_cos=new JButton("cos");button_minus=new JButton("-");JPanel panel5=new JPanel();panel5.setLayout(new GridLayout(1,5,4,4));this.add(panel5);button_0=new JButton("0");button_point=new JButton(".");button_equal=new JButton("=");button_sin=new JButton("sin");button_plus=new JButton("+");panel1.add(button_sqrt);panel1.add(button_plusminus);panel1.add(button_exp);panel1.add(button_CE);panel1.add(button_cancel);panel2.add(button_7);panel2.add(button_8);panel2.add(button_9);panel2.add(button_log);panel2.add(button_divide);panel3.add(button_4);panel3.add(button_5);panel3.add(button_6);panel3.add(button_tan);panel3.add(button_multiply);panel4.add(button_1);panel4.add(button_2);panel4.add(button_3);panel4.add(button_cos);panel4.add(button_minus);panel5.add(button_0);panel5.add(button_point);panel5.add(button_equal);panel5.add(button_sin);panel5.add(button_plus);button_sqrt.addActionListener(this);button_plusminus.addActionListener(this);button_exp.addActionListener(this);button_CE.addActionListener(this);button_cancel.addActionListener(this);button_7.addActionListener(this);button_8.addActionListener(this);button_9.addActionListener(this);button_log.addActionListener(this);button_divide.addActionListener(this);button_4.addActionListener(this);button_5.addActionListener(this);button_6.addActionListener(this);button_tan.addActionListener(this);button_multiply.addActionListener(this);button_1.addActionListener(this);button_2.addActionListener(this);button_3.addActionListener(this);button_cos.addActionListener(this);button_minus.addActionListener(this);button_0.addActionListener(this);button_point.addActionListener(this);button_equal.addActionListener(this);button_sin.addActionListener(this);button_plus.addActionListener(this);this.addWindowListener(new WinClose()); //注册窗口监听器this.setVisible(true);}private void addmyMenu() //菜单的添加{JMenuBar menubar=new JMenuBar();this.add(menubar);JMenu m1=new JMenu("选项");JMenu m2=new JMenu("进制转换");JMenuItem m1_exit=new JMenuItem("退出");m1_exit.addActionListener(this);JMenuItem m2_ejz=new JMenuItem("二进制");m2_ejz.addActionListener(this);JMenuItem m2_bjz=new JMenuItem("八进制");m2_bjz.addActionListener(this);JMenu m3 = new JMenu(" 帮助");JMenuItem m3_Help = new JMenuItem("作者");m3_Help.addActionListener(this);dialog = new Dialog(this,"关于",true); //模式窗口 dialog.setSize(240,80);label_dialog = new Label("",Label.CENTER); //标签的字符串为空,居中对齐dialog.add(label_dialog);dialog.addWindowListener(this); //为对话框注册窗口事件监听器m1.add(m1_exit);menubar.add(m1);m2.add(m2_ejz);m2.add(m2_bjz);menubar.add(m2);m3.add(m3_Help);menubar.add(m3); }public void actionPerformed(ActionEvent e) //按钮的单击事件处理方法{if(e.getSource().equals(button_1)||e.getSource().equals(button_2)||e.getSource().equals(button_3)||e.getSource().equals(button_4)||e.getSource().equals(button_5)|| e.getSource().equals(button_6)||e.getSource().equals(button_7)|| e.getSource().equals(button_8)||e.getSource().equals(button_9) ||e.getSource().equals(button_0)||e.getSource().equals(button_point)||e.getSource().equals(button_plusmin us)||e.getSource().equals(button_cancel)||e.getSource().equals(button_CE)){ //非运算符的处理方法String input=e.getActionCommand();if (start){displayField.setText("");start=false;if(input.equals("+/-"))displayField.setText(displayField.getText()+"-");}if(!input.equals("+/-")){String str=displayField.getText();if(input.equals("C")) //退格键的实现方法{if(str.length()>0)displayField.setText(str.substring(0,str.length()-1));}else if(input.equals("CE")) //清零键的实现方法{displayField.setText("0");start=true;}elsedisplayField.setText(displayField.getText()+input);}}else if (e.getActionCommand()=="二进制") //二进制的转换{int n=Integer.parseInt(displayField.getText());displayField.setText(Integer.toBinaryString(n));}else if (e.getActionCommand()=="八进制") //八进制的转换{int n=Integer.parseInt(displayField.getText());displayField.setText(Integer.toOctalString(n));}else if (e.getActionCommand()=="退出") //选项中退出的处理方法{System.exit(0);}else if (e.getActionCommand()=="作者") //按下'帮助'菜单栏中用法的处理方法{label_dialog.setText("熊瑛琪制作 \n学号:080320618");dialog.setLocation(400,250);dialog.setVisible(true);}else //各运算符的识别{String command=e.getActionCommand();if(start){lastCommand=command;}else{calculate(Double.parseDouble(displayField.getText()));lastCommand=command;start=true;}}}public void calculate(double x) //各运算符的具体运算方法 {double d=0;if (lastCommand.equals("+"))result+= x;else if (lastCommand.equals("-"))result-=x;else if (lastCommand.equals("*"))result*=x;else if (lastCommand.equals("/"))result/=x;else if (lastCommand.equals("="))result=x;else if (lastCommand.equals("sqrt")){d=Math.sqrt(x);result=d;}else if (lastCommand.equals("exp")){d=Math.exp(x);result=d;}else if (lastCommand.equals("log")){d=Math.log(x);result=d;}else if (lastCommand.equals("tan")){d=Math.tan(x);result=d;}else if (lastCommand.equals("cos")){d=Math.cos(x);result=d;}else if (lastCommand.equals("sin")){d=Math.sin(x);result=d;}displayField.setText(""+ result);}public void windowClosing(WindowEvent e){if(e.getSource()==dialog)dialog.setVisible(false); //隐藏对话框elseSystem.exit(0);}public void windowOpened(WindowEvent e) { }public void windowActivated(WindowEvent e) { }public void windowDeactivated(WindowEvent e) { }public void windowClosed(WindowEvent e) { }public void windowIconified(WindowEvent e) { }public void windowDeiconified(WindowEvent e) { }public static void main(String args[]){Calculator calculator=new Calculator();}}class WinClose implements WindowListener{public void windowClosing(WindowEvent e) //单击窗口关闭按钮时触发并执行实现窗口监听器接口{System.exit(0); //结束程序运行}public void windowOpened(WindowEvent e){}public void windowActivated(WindowEvent e){}public void windowDeactivated(WindowEvent e){}public void windowClosed(WindowEvent e){}public void windowIconified(WindowEvent e){}public void windowDeiconified(WindowEvent e){}}程序运行在对程序进行测试时发现“sin”函数出现异常点击“sin”然后输入“90”出现以下情况经过对程序代码的检查发现在下面方法中public void calculate(double x) //各运算符的具体运算方法{double d=0;if (lastCommand.equals("+"))result+= x;else if (lastCommand.equals("-"))result-=x;else if (lastCommand.equals("*"))result*=x;else if (lastCommand.equals("/"))result/=x;else if (lastCommand.equals("="))result=x;else if (lastCommand.equals("sqrt")){d=Math.sqrt(x);result=d;}else if (lastCommand.equals("exp")){d=Math.exp(x);result=d;}else if (lastCommand.equals("log")){d=Math.log(x);result=d;}else if (lastCommand.equals("tan")){d=Math.tan(x);result=d;}else if (lastCommand.equals("cos")){d=Math.cos(x);result=d;}displayField.setText(""+ result); }发现遗漏以下代码else if (lastCommand.equals("sin")){d=Math.sin(x);result=d;}修改后再次进行测试输入“1.5707963”(约为0.5*pi)再键入“sin”得以下结果可见程序修改成功。

J2me手机游戏存储玩家分数源码.

J2me手机游戏存储玩家分数源码.

J2me手机游戏存储玩家分数源码package shiyan23;import java.io.*;import javax.microedition.lcdui.*;import javax.microedition.rms.*;public class Displayable1 extends Form {public Form form;/** Constructor */public TextField t1;public TextField t2;private RecordStore rs;private Display dis;public Displayable1(Display dis) {super("");this.dis=dis;this.form=this;try {jbInit();} catch (Exception e) {e.printStackTrace();}}/**Component initialization*/private void jbInit() throws Exception {// Set up this Displayable to listen to command eventssetCommandListener(new CommandListener() {public void commandAction(Command command, Displayable displayable) {this_commandPerformed(command, displayable);}});// add the Exit commandaddCommand(new Command("Exit", Command.EXIT, 1));addCommand(new Command("存储", Command.SCREEN, 1));addCommand(new Command("高分榜", Command.SCREEN, 1));t1 = new TextField("游戏玩家", "play1", 10, TextField.ANY);t2 = new TextField("当前分数", "0", 10, TextField.NUMERIC);append(t1);append(t2);}/**Handle command events*/public void this_commandPerformed(Command command, Displayable displayable) { /** @todo Add command handling code */if (command.getCommandType() == Command.EXIT) {// stop the MIDletMIDlet1.quitApp();}if (command.getLabel().equals("存储")) {try {rs=RecordStore.openRecordStore("shiyan23", true);ByteArrayOutputStream bo=new ByteArrayOutputStream();DataOutputStream dao = new DataOutputStream(bo);dao.writeUTF(t1.getString());dao.writeInt(Integer.parseInt(t2.getString()));byte[] data=bo.toByteArray();rs.addRecord(data, 0, data.length);} catch (Exception e) {System.out.println("存储过程出现异常");e.printStackTrace();}finally{try {rs.closeRecordStore();}catch (RecordStoreException ex) {}}}if(command.getLabel().equals("高分榜")){try {rs=RecordStore.openRecordStore("shiyan23", true);myFilter mf=new myFilter();MyComparator mc=new MyComparator();RecordEnumeration en=rs.enumerateRecords(mf,mc,true);Form f=new Form("游戏高分榜");f.addCommand(new Command("返回", Command.BACK,1));f.setCommandListener(new CommandListener() {public void commandAction(Command command, Displayable displayable) {dis.setCurrent(form);}} );f.append("姓名分数");int i=0;while(en.hasNextElement()&&(i<5))//是否有下一条{byte dat[]=en.nextRecord();//得到下一条ByteArrayInputStream bis=new ByteArrayInputStream(dat);DataInputStream dis=new DataInputStream(bis);String getname=dis.readUTF();//读取昵称int getscore=dis.readInt();//读取分数f.append(getname+""+getscore);i++;}dis.setCurrent(f);} catch (Exception e) {System.out.println("读取过程出现异常");e.printStackTrace();}finally{try {rs.closeRecordStore();}catch (RecordStoreException ex) {}}}}}//自定义过滤器class myFilter implements RecordFilter{public boolean matches(byte[] dat) {ByteArrayInputStream bis=new ByteArrayInputStream(dat);DataInputStream dis=new DataInputStream(bis);try{dis.readUTF();//获取昵称int score=dis.readInt();//获取分数if(score>=10000){return true;}}catch(Exception e ){}return false;}}class MyComparator implements RecordComparator{public int compare(byte[] rec1,byte[] rec2){int score1=0,score2=0;ByteArrayInputStream bis=new ByteArrayInputStream(rec1);DataInputStream dis=new DataInputStream(bis);try{dis.readUTF();//获取昵称score1=dis.readInt();//获取分数}catch(Exception e ){}bis=new ByteArrayInputStream(rec2);dis=new DataInputStream(bis);try{dis.readUTF();//获取昵称score2=dis.readInt();//获取分数}catch(Exception e ){}if(score1==score2){return RecordComparator.EQUIV ALENT;}//ifif(score1>score2){return RecordComparator.PRECEDES;} else{return RecordComparator.FOLLOWS;}//else}}package shiyan23;import javax.microedition.midlet.*;import javax.microedition.lcdui.*;/*** <p>Title: </p>** <p>Description: </p>** <p>Copyright: Copyright (c) 2009</p>** <p>Company: </p>** @author not attributable* @version 1.0*/public class MIDlet1 extends MIDlet {static MIDlet1 instance;Display dis=Display.getDisplay(this);Displayable1 displayable = new Displayable1(dis);public MIDlet1() {instance = this;}public void startApp() {Display.getDisplay(this).setCurrent(displayable);}public void pauseApp() {}public void destroyApp(boolean unconditional) {}public static void quitApp() {instance.destroyApp(true);instance.notifyDestroyed();instance = null;}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

J2ME计算器源码import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Midlet extends MIDlet {
private Display display;
private CalcCanvas mycanvas;
public Midlet(){
display=Display.getDisplay(this);
mycanvas=new CalcCanvas();
}
public void startApp() {
display.setCurrent(mycanvas);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) { }
}
import java.io.IOException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
public class CalcCanvas extends Canvas{
int status;
private Image image = null;
/**输入第一个数字状态*/
final int INPUT_FIRST = 1;
/**输入第二个数字状态*/
final int INPUT_SECOND = 3;
/**输入运算符号状态*/
final int INPUT_FLAG = 2;
界面图片/**绘制内容右下角的x坐标*/
int x = 50;
/**绘制内容右下角的x坐标*/
int y = 60;
/**行高*/
int lineHeight = 10;
/**第一个数字的值*/
int firstNum = 0;
/**第二个数字的值*/
int secondNum = 0;
/**运算符号,0无意义,1代表+,2代表减、3乘4除*/ int flag = 0;
/**屏幕宽度*/
int w;
/**屏幕高度*/
int h;
/**运算符数组*/
String[] sFlag = {"+","-","*","/"};
public CalcCanvas(){
try{
image = Image.createImage("/calc.png");
}catch(IOException e){
System.out.println(e);
}
//初始化状态为输入第一个数字状态
status = INPUT_FIRST;
//设置全屏幕
setFullScreenMode(true);
//获得屏幕高度和宽度
h = getHeight();
w = getWidth();
}
protected void paint(Graphics g) {
//清屏
g.setColor(0xffffff);
g.fillRect(0, 0, 255, 208);
g.setColor(255);
g.drawRect(5, 42, 170, 16); // 结果显示条
g.drawImage(image,2,60,Graphics.TOP|Graphics.LEFT);
//绘制按钮文字
g.drawString("=", w,h,
Graphics.RIGHT | Graphics.BOTTOM);
g.drawString("C", 0,h,
Graphics.LEFT | Graphics.BOTTOM);
//根据状态值确定绘制的内容和位置
switch(status){
case INPUT_FIRST:
//绘制第一个数字
g.drawString("" + firstNum, x, y,
Graphics.RIGHT | Graphics.BOTTOM);
break;
case INPUT_FLAG:
//绘制第一个数字
g.drawString("" + firstNum, x- lineHeight, y ,
Graphics.RIGHT | Graphics.BOTTOM);
//绘制运算符号
g.drawString(sFlag[flag - 1], x, y,
Graphics.RIGHT | Graphics.BOTTOM);
break;
case INPUT_SECOND:
//绘制第一个数字
g.drawString("" + firstNum, x- 2 * lineHeight, y ,
Graphics.RIGHT | Graphics.BOTTOM);
//绘制运算符号
g.drawString(sFlag[flag - 1], x- lineHeight, y ,
Graphics.RIGHT | Graphics.BOTTOM);
//绘制第二个数字
g.drawString("" + secondNum, x, y,
Graphics.RIGHT | Graphics.BOTTOM);
break;
}
}
public void keyPressed(int keyCode){
//按钮C的处理
if(keyCode == -6){ //左软键
//根据状态值确定清除的内容
switch(status){
case INPUT_FIRST:
firstNum /=10;
break;
case INPUT_FLAG:
//切换到输入第一个数字状态
status = INPUT_FIRST;
//清除运算符号
flag = 0;
break;
case INPUT_SECOND:
//清除第二个数字
secondNum /= 10;
//如果第二个数字为0,则切换到输入运算符状态
if(secondNum == 0){
status = INPUT_FLAG;
}
break;
}
}
if(keyCode == -7){ //按钮=的处理
//如果处于输入第二个数字状态,且第二个数字不是0
if((status == INPUT_SECOND) && (secondNum != 0)){
//计算结果,并把结果赋值给第一个数字
switch(flag){
case 1:
firstNum += secondNum;
break;
case 2:
firstNum -= secondNum;
break;
case 3:
firstNum *= secondNum;
break;
case 4:
firstNum /= secondNum;
break;
}
//恢复状态到输入第一个数字状态
status = INPUT_FIRST;
//清除运算符和第二个数字
flag = 0;
secondNum = 0;
}
}
//输入的是数字键
if((keyCode >= KEY_NUM0) && (keyCode <= KEY_NUM9)){
//如果是输入第一个数字状态
switch(status){
case INPUT_FIRST:
firstNum = firstNum * 10 + (keyCode - KEY_NUM0);
break;
case INPUT_SECOND:
secondNum = secondNum * 10 + (keyCode - KEY_NUM0);
break;
case INPUT_FLAG:
//切换到输入第二个数字状态
status = INPUT_SECOND;
//记忆输入的数字
secondNum = secondNum * 10 + (keyCode - KEY_NUM0);
break;
}
}
//按星号实现输入运算符号
if(keyCode == KEY_STAR){
//如果当前是输入第一个数字状态或输入运算符状态
if((status == INPUT_FIRST) || (status == INPUT_FLAG)){
//输入运算符
if(flag < 4){
flag++;
}else{
flag = 1;
}
//设置状态为输入运算符状态
status = INPUT_FLAG;
}
}
//重绘
repaint();
}
}。

相关文档
最新文档