java - 确定按钮不起作用

标签 java java-me midp lcdui

请看下面的代码。

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

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);

    }
}

最佳答案

在此代码片段中 commandAction不会被调用,因为你忘记了 setCommandListener :

Sets a listener for Commands to this Displayable...

在 startApp 中,这将如下所示:

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

另外,作为 pointed in another answer ,即使在您设置了监听器之后,它也会错过命令,因为代码检查错误 - 在 Java 中,"ok" 不会 equals “确定”

实际上,鉴于此处只有一个命令,因此无需 checkin commandAction - 您可以直接进入那里的 showInput - 同样,直到只有一个 命令。


在此代码片段中值得添加的另一件事是 logging .

通过适当的日志记录,很容易在模拟器中运行代码,查看控制台并发现例如根本没有调用 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);
}
// ...

关于java - 确定按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11798920/

相关文章:

java - Spark rest api 服务器部署

java - JPQL 使用日期时间的日期部分查询实体的 java.util.Date 字段

java - j2me中如何将12小时时间转换为24小时时间?

java - 非最终静态字符串是否比静态最终字符串更有效?

java - Tomcat 日志策略

java-me - 开发移动应用程序

java-me - 如何在J2ME 中添加按钮?

java-me - j2me中是否可以作为后台进程上传数据?

java - JTextField setText() 方法不更新字段