1

请看下面的代码。

在这里,“确定”按钮没有响应。

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

public class TexyFieldExample extends MIDlet implements CommandListener
{
    private Form form;
    private Display display;
    private TextField name, company;
    private Command ok;

    public TexyFieldExample()
    {        
        name = new TextField("Name","",30,TextField.ANY);
        company = new TextField("Company","",30,TextField.ANY);
        ok = new Command("OK",Command.OK,2);

    }

    public void startApp()
    {
        form = new Form("Text Field Example");
        display = Display.getDisplay(this);

        form.append(name);
        form.append(company);
        form.addCommand(ok);

        display.setCurrent(form);

    }

    public void pauseApp()
    {

    }

    public void destroyApp(boolean destroy)
    {
        notifyDestroyed();
    }

    public void commandAction(Command c, Displayable d) 
    {
        String label = c.getLabel();

        if(label.equals("ok"))
        {
            showInput();
        }
    }

    private void showInput()
    {
        form = new Form("Input Data");
        display = Display.getDisplay(this);

        form.append(name.getString());
        form.append(company.getString());

        display.setCurrent(form);

    }
}
4

1 回答 1

4

在此代码段中,不会调用commandAction ,因为您忘记了setCommandListener

为这个 Displayable 设置一个 Commands 的监听器...

在 startApp 中,这将如下所示:

    //...
    form.addCommand(ok);
    // set command listener
    form.setCommandListener(this);
    //...

此外,正如另一个答案中所指出的,即使您设置了侦听器,它也会错过命令,因为代码检查它错误 - 在 Java 中,"ok"等于 "OK"

实际上,鉴于这里只有一个命令,因此无需签入 commandAction - 您可以直接进入showInput那里 - 再次,直到只有一个命令。


在此代码段中值得添加的另一件事是日志记录

使用适当的日志记录,只需在模拟器中运行代码,查看控制台并发现根本没有调用例如 commandAction,或者没有正确检测到该命令将非常容易:

// ...
public void commandAction(Command c, Displayable d) 
{
    String label = c.getLabel();
    // log the event details; note Displayable.getTitle is available since MIDP 2.0
    log("command  s [" + label + "], screen is [" + d.getTitle() + "]");

    if(label.equals("ok"))
    {
        // log detection of the command
        log("command obtained, showing input");
        showInput();
    }
}

private void log(String message)
{
    // show message in emulator console
    System.out.println(message);
}
// ...
于 2012-08-03T16:05:32.060 回答