使用j2me和lwuit在后台下载图像

时间:2012-04-02 12:09:45

标签: java java-me lwuit

我有一个要从互联网上下载的图像列表,并列在一个列表中,每个图像旁边都有说明文字。

我现在遇到的问题是,在我理解下载图像时应用程序会冻结。

我创建了一个线程来进行下载,该类在下面。我使用start方法启动线程,但在我使用run之前,图像将为空。

public class GetImage extends Thread {

public String imgString;
private String url;
private Label label;
public Image img = null;

public GetImage(String url, Label label){
    this.url = url;
    this.label = new Label();
    this.label = label;
}

public Image getPic()
{

    return img;
}
public void run()
{
   this.getImage_(); 
   this.label.setIcon(img.scaledHeight(60));

}

public void getImage_()
{
    HttpConnection hc = null;
    DataInputStream dis = null;
    DataOutputStream dos = null;
    StringBuffer messageBuffer  = new StringBuffer();

     try{
        hc = (HttpConnection)Connector.open(this.url,Connector.READ);
        dis = new DataInputStream(hc.openDataInputStream());
        int ch;
        long len = hc.getLength();
        if(len != -1)
        {
            for(int i=0; i < len; i++)
                if((ch = dis.read())!=-1)
                    messageBuffer.append((char)ch);
        }
        else
        {
            while((ch = dis.read()) != -1)
                messageBuffer.append((char)ch);
        }

        this.img = Image.createImage(messageBuffer.toString().getBytes(),0,messageBuffer.toString().length());
        dis.close();
    }
    catch(IOException ae){
        messageBuffer.append("Error");
    }
    finally{
        try {
            if (hc != null) hc.close();
        }
        catch (IOException ignored) {}
        try {
            if (dis != null) dis.close();
        }
        catch (IOException ignored) {}
        try {
            if (dos != null) dos.close();
        }
        catch (IOException ignored) {}
    }

   //return this.img;
}

}

和listrenderer显示列表:

public class ListRenderer extends Label implements ListCellRenderer {

public ListRenderer()
{
    super();
}

public Component getListCellRendererComponent(List list, Object o, int i, boolean bln) {
     //cast the value object into a Content

    Contents entry = (Contents)o;
    //get the icon of the Content and set it for this label
    this.setIcon(entry.getIcon());
    //get the text of the Content and set it for this label
    this.setText(entry.getText());
    //set transparency
    getStyle().setBgTransparency((byte)128);
    //set background and foreground colors
    //depending on whether the item is selected or not
    if(bln)
    {
        getStyle().setBgColor(0xffcc33);
        getStyle().setFgColor(0x000000);
    }
    else
    {
       getStyle().setBgColor(0xffffff);

    }
    return this;
}

public Component getListFocusComponent(List list) {
    setText("");
    setIcon(null);
    getStyle().setBgColor(0xffcc33);
    getStyle().setBgTransparency(80);
    return this;
}

}

任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

你得到的评论可能是正确的。这个blog post显示的内容与您尝试实现的内容类似。它在Codename One中,但大多数代码也适用于LWUIT。