2016-03-05 94 views
0

我对J2ME编程相对较新。我被要求建立一个显示5个水果名称的程序,当点击“显示”时,它显示各自的图像。虽然我的代码是正确的,但图像不显示,我得到的只是下一张表单上的黑屏。图像未在J2ME Midlet中显示

CODE:

import javax.microedition.lcdui.* ; 
import javax.microedition.midlet.*; 
/** 
* @author Ashutosh 
*/ 
public class Midlet extends MIDlet implements CommandListener 
{ 
    private Display display ; 
    private Form f,f1 ; 
    ChoiceGroup cg ; 
    private Image image ; 
    Command cmd = new Command("SHOW" , Command.OK , 1) ; 
    Command cmd1 = new Command("BACK" , Command.BACK , 1) ; 
    public Midlet() 
    { 
     try 
     { 
      image = Image.createImage("Apple.png"); 
     } 
     catch (Exception e) 
     { 

     } 
    }   
    public void startApp() 
    { 
     f = new Form("Home") ; 
     f1 = new Form("Show Screen") ; 
     cg=new ChoiceGroup("Select Apple:",Choice.EXCLUSIVE); 
     display = Display.getDisplay(this) ; 
     cg.append("Apple",null) ; 
     cg.append("Banana",null) ; 
     cg.append("Cherry",null) ; 
     cg.append("Kiwi",null) ; 
     cg.append("Mango",null) ; 
     f.append(cg) ; 
     f.addCommand(cmd); 
     f1.addCommand(cmd1); 
     display.setCurrent(f); 
     f.setCommandListener(this); 
     f1.setCommandListener(this); 
    } 

    public void pauseApp() 
    { 
    } 

    public void destroyApp(boolean unconditional) 
    { 
    } 

    public void commandAction(Command c, Displayable d) 
    { 
     int a = cg.getSelectedIndex() ; 
     if(c == cmd) 
     { 
      display.setCurrent(f1); 
      switch(a) 
      { 
       case 0 : f1.append(image) ; 
       default : System.exit(0) ;  
      } 
     } 
     if(c == cmd1) 
     { 
      display.setCurrent(f); 
     } 
    } 
} 

在此先感谢。

回答

0

我找到了解决办法。 您必须将图像放入只在您的IDE中创建的“资源”目录中。将图像添加到磁盘上的源文件夹是无关紧要的。

msell的以下回答有效地解决了这个问题。 https://stackoverflow.com/a/1332470/4786292

0

如果你的图片是在同一个包你的MIDlet放在试试:

image = Image.createImage("/Apple.png"); 

,而不是

image = Image.createImage("Apple.png"); 

而且不要忘了把e.printStackTrace();你的catch块中,这样的情况下一个错误发生,你可以弄明白。

UPDATE: 相反的:

 display.setCurrent(f1); 
     switch(a) 
     { 
      case 0 : f1.append(image) ; 
      default : System.exit(0) ;  
     } 

尝试:

 switch(a) 
     { 
      case 0 : f1.append(image) ; 
      default : System.exit(0) ;  
     } 

     display.setCurrent(f1); 
+0

我最初只尝试过,但由于它没有工作,我切换到此。谢谢,不过。 –

+0

它现在工作吗? –

+0

否,正在报告空指针异常。 –