Вопрос

Please have a look at the following code.

In here, the "OK" button is not responding.

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

    }
}
Это было полезно?

Решение

In this code snippet commandAction won't be invoked because you forgot to setCommandListener:

Sets a listener for Commands to this Displayable...

In startApp, this would look about as follows:

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

Also, as pointed in another answer, even after you set the listener, it will miss the command because code checks it wrong - in Java, "ok" does not equals "OK".

Actually, given that there's only one command here, there is no need to check in the commandAction - you can proceed straight into showInput there - again, until there's only one command.


Another thing worth adding in this code snippet is logging.

With appropriate logging, it would be dead easy to just run code in emulator, look into console and find out that eg commandAction isn't invoked at all, or that command isn't detected properly:

// ...
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);
}
// ...
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top