请看下面的代码。
在这里,“确定”按钮没有响应。
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:
将命令的侦听器设置为此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);
}
// ...