请查看以下代码。
在这里,“确定”按钮没有响应。
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);
}
}
答案 0 :(得分:4)
在此代码段中commandAction将不会被调用,因为您忘记了setCommandListener:
将命令的侦听器设置为此Displayable ...
在startApp中,这看起来如下:
//...
form.addCommand(ok);
// set command listener
form.setCommandListener(this);
//...
另外,作为pointed in another answer,即使在设置了侦听器之后,它也会错过命令,因为代码检查错误 - 在Java中,"ok"
没有equals "OK"
实际上,假设这里只有一个命令,则无需检查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);
}
// ...