2012-08-03 42 views
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

在此代碼段commandAction將不會被調用,因爲你忘了setCommandListener

設置命令的監聽器,這可顯示...

在的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); 
} 
// ... 
+2

更具體地說,他需要執行'ok.setCommandListener(this);'來獲得他想要的行爲。 – kurtzbot 2012-08-03 16:13:24

+0

非常感謝您的回答!有效!謝謝:) – 2012-08-04 14:01:59

+1

@kurtzbot:ok按鈕沒有這樣的方法。我檢查了。 – 2012-08-04 14:03:30