J2ME:实现从本地下载图片

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.Vector;

public class ViewImage2 extends MIDlet implements CommandListener{
  Display display;
  Form myform=null;
  String url="http://localhost:8080/pic/1.gif";      //8080tomcat服务器端口,若用的是IIS将端口改为8088
   Command backCommand=new Command("返回",Command.BACK,0);
  Command submitCommand=new Command("请求",Command.OK,2);
  Command exitCommand=new Command("退出",Command.STOP,3);
  private Download download;
 public ViewImage2() {}

 protected void destroyApp(boolean arg0) {}

 protected void pauseApp() {}

 protected void startApp()  {
 display=Display.getDisplay(this);
 myform=new Form("显示图像");
 myform.addCommand(submitCommand);
    myform.addCommand(exitCommand);
    myform.setCommandListener(this);
    display.setCurrent(myform);
 }

 public void commandAction(Command c, Displayable d) {
  if(c==exitCommand)
  {
   destroyApp(true);
   notifyDestroyed();
  }
  else if(c==backCommand)
  {
   display.setCurrent(myform);
  }
  else if(c==submitCommand)
  {
   download=new Download(this);
   download.start();
  }
 }
 class Download implements Runnable {
      
  ViewImage2 midlet;
  public Download(ViewImage2 midlet) {
    this.midlet=midlet;
    display=Display.getDisplay(midlet);
  }

  public void start() {
   // TODO Auto-generated method stub
   Thread t=new Thread(this);
   t.start();
  }

  public void run() {
   DataInputStream dis=null;
   Image img=null;
   try{
    HttpConnection conn=(HttpConnection) Connector.open(url);
    int len=(int) conn.getLength();
    if(len>0)
    {
     dis=conn.openDataInputStream();
     byte[] data=new byte[len];
     dis.readFully(data);
     img=Image.createImage(data,0,len);
     Form f=new Form("图像");
     ImageItem imageItem=new ImageItem("",img,ImageItem.LAYOUT_NEWLINE_AFTER|ImageItem.LAYOUT_CENTER,null);
     f.append(imageItem);
     display.setCurrent(f);
     
    }
    else
    {
     showAlert("没有信息");
    }
    dis.close();
    conn.close();
   }
   catch(Exception e)
   {
    e.printStackTrace();
    showAlert(e.getMessage());
   }
   
  }

  private void showAlert(String err) {
   Alert a=new Alert("");
   a.setString(err);
   a.setTimeout(Alert.FOREVER);
   display.setCurrent(a);
   
  }

 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值