⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httpimage.java

📁 《精通JAVA手机游戏与应用程序设计》随书光盘
💻 JAVA
字号:
// HttpImage.java

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

public class HttpImage extends MIDlet implements CommandListener {

	private Command exitCommand, loadCommand;

	private Form mainForm;

	private ImageItem imgItem;

	private TextField tf;

	public HttpImage() {
		mainForm = new Form("下载并显示图片资源");
		tf = new TextField("图片地址", "http://127.0.0.1:8080/book.png", 120,
				TextField.URL);
		//设置控件的布局
		tf.setLayout(Item.LAYOUT_NEWLINE_AFTER);
		imgItem = new ImageItem("Image", null, Item.LAYOUT_CENTER, "image");
		imgItem.setPreferredSize(mainForm.getWidth(), 80);
		imgItem.setLayout(Item.LAYOUT_VEXPAND | Item.LAYOUT_2);

		mainForm.append(tf);
		mainForm.append(imgItem);

		exitCommand = new Command("退出", Command.EXIT, 1);
		loadCommand = new Command("下载", Command.SCREEN, 1);
		mainForm.addCommand(exitCommand);
		mainForm.addCommand(loadCommand);
		mainForm.setCommandListener(this);
	}

	protected void startApp() throws MIDletStateChangeException {
		Display.getDisplay(this).setCurrent(mainForm);
	}

	protected void pauseApp() {
	}

	protected void destroyApp(boolean p1) {
	}

	public void commandAction(Command c, Displayable d) {
		if (c == exitCommand) {
			destroyApp(false);
			notifyDestroyed();
		} else if (c == loadCommand) {
			//开启一个新的网络连接后台线程
			new DownLoadImage(mainForm, imgItem, tf.getString());
		}
	}

	private class DownLoadImage extends Thread {
		private String imageURL;

		private Form form;

		private ImageItem imageItem;

		public DownLoadImage(Form f, ImageItem i, String url) {
			form = f;
			imageItem = i;
			imageURL = url;
			this.start();
		}

		public void run() {
			Image imgLoad = null;
			try {
				imgLoad = getPngImage(imageURL);
			} catch (Exception e) {
				System.out.println("error = " + e.getMessage());
			}
			form.setTicker(null);
			if (imgLoad != null)
				imageItem.setImage(imgLoad);
		}

		public Image getPngImage(String url) throws IOException, Exception {
			HttpConnection c = null;
			InputStream is = null;
			Image image = null;
			try {
				c = (HttpConnection) Connector.open(url);
				//判断是否连接成功
				int rc = c.getResponseCode();
				if (rc != HttpConnection.HTTP_OK) {
					throw new Exception(c.getResponseMessage());
				}
				//获得图像的二进制数据
				is = c.openInputStream();
				//把二进制数据转换为Image对象
				image = Image.createImage(is);
			} catch (IOException e) {
				System.out.println("错误:" + e.getMessage());
			} finally {
				if (is != null)
					is.close();
				if (c != null)
					c.close();
			}
			return image;
		}
	}

	

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -