這不符合您的預期。
我看到已經有一些解決方案,但我覺得更多關於實際正在進行的討論可能會有所幫助。
當您撥打frm.setCommandListener(new CommandListener() { ... })
時,代碼會向用戶顯示一個對話框,您可以在其中鍵入一些文本並提交,但代碼不會停止並等待用戶完成。代碼繼續執行 - 不會產生結果。只有在用戶完成鍵入並提交之後,纔會回叫您以處理結果 - 這可能會晚得多,或根本不會。
我猜你有一些代碼調用此方法,如:
public void someMethod(int foo, String bar) {
[...]
String result = MyInputForm.showInputDialog();
// do something with the result
System.out.println("hey, got a result "+ result);
[...]
}
相反,你需要重組這一點。首先寫一個輔助類處理結果:
公共靜態類myCallBack函數{
public MyCallBack(... /* here pass in what you need to process the result*/) {
... remember necessary stuff in instance variables
}
public void processResult(String result) {
// do something with the result
System.out.println("hey, got a result "+ result);
[...]
}
}
然後主叫方不會只是:
public void someMethod(int foo, String bar) {
[...]
MyInputForm.showInputDialog(new MyCallBack(... here pass in stuff ...));
[...]
}
和實際的代碼必須改爲:
public static String showInputDialog(final MyCallBack callback) {
Form frm = new Form();
final Command cmd = new Command("Ok");
final TextField txt = new TextField("Enter the text", null, 1024, 0);
frm.addCommand(cmd);
frm.append(txt);
frm.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c == cmd) {
return callback.processResult(txt.getString());
} else {
return; // or just omit the else part
}
}
});
}
兩個問題:
- 這種編程方式讓人感覺非常倒退,但它確實是它的工作方式。
- 什麼感覺不對的是,我需要定義除
CommandListener
以外的第二個幫手類。這真的不是很好的風格。我希望它可以得到改進,但由於我沒有看到完整的代碼(無論如何這將是太多的信息),我不得不讓它改進代碼並擺脫混亂。雖然我覺得你想擁有一個模塊化的,可重用的輸入對話助手,但這可能不是最好的方法;更好地定義Form
,TextField
和Command
直接您需要結果並獲得該運行。讓它在運行後的第二步中重複使用。
沒有辦法做到這一點。除非你是'CommandListener'的作者。 – madhead 2013-02-10 13:24:31
@madhead'CommandListener'是一個內置的接口,它具有'CommandAction'方法。我無法更改重寫方法的簽名 – user1234524521 2013-02-10 13:28:41
您不能像這樣返回它,因爲您不知道commandAction何時運行。在這個方法中,你只需要把它作爲一個監聽器。 – BobTheBuilder 2013-02-10 13:36:05