我写了以下Java Application

import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;


public class JavaApplication6 extends MIDlet
{
private static Form clockForm=null;
private static StringItem clockItem=new StringItem("hello", "World!");
private static ClockTask task=null;
private static Timer timer=null;

static class ClockTask extends TimerTask
{
private int count=0;
        @Override
public void run()
{
count++;
clockItem.setText("hello "+count);
}
}
public static  void JavaApplication6() throws Exception
{
clockForm=new Form("Clock");
clockItem=new StringItem("","0");
clockForm.append(clockItem);
}

    @Override
public  void startApp()
{
task=new ClockTask();
timer=new Timer();
timer.schedule(task,1000,1000);
Display.getDisplay(this).setCurrent(clockForm);}

    @Override
public void pauseApp()
{}

public void destroyApp(boolean unconditional)
{}


    public static void main(String[] args) {


        JavaApplication6 test=new JavaApplication6();
        test.startApp();



    }
}


但是当我运行它时,它在exception的最后一行给出了以下startApp()

Exception in thread "main" java.lang.NullPointerException
    at javax.microedition.lcdui.Display.<init>(Display.java:420)
    at javax.microedition.lcdui.Display.getDisplay(Display.java:447)
    at javaapplication6.JavaApplication6.startApp(JavaApplication6.java:42)
    at javaapplication6.JavaApplication6.main(JavaApplication6.java:56)

最佳答案

您创建的静态方法JavaApplication6命名为它的构造函数。但事实并非如此。所以说JavaApplication6 test=new JavaApplication6();时不会调用它。因此clockForm仍未初始化,即null。所以,线

Display.getDisplay(this).setCurrent(clockForm);

此时抛出NPE的原因是clockFormnull

解决方案是从行static void中删除​​public static void JavaApplication6() throws Exception。它看起来像

public JavaApplication6() throws Exception

在这种情况下,它将成为构造函数,并且一切正常。

祝好运。

10-07 12:24
查看更多