1
在javafx2應用程序中,組合框應顯示項目列表,爲簡單起見,它們爲String
。javafx-2組合框轉換器:方法toString(T對象)未調用空值
此列表包含一個null
項目,因爲我希望允許用戶別無選擇。
因爲我在玩ComboBox的轉換器屬性,我想知道我是否可以用它爲無選擇的情況提供一個很好的表示,例如「[none]」而不是空行。
但我發現toString(Object對象)永遠不會被調用爲null項目。
下面是再現案例的最短代碼。包含版本信息。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class T05 extends Application {
@Override public void start(Stage primaryStage) throws Exception {
System.out.println(System.getProperty("java.runtime.version"));
System.out.println(System.getProperty("javafx.runtime.version"));
System.out.println(System.getProperty("os.version"));
System.out.println(System.getProperty("os.name"));
ComboBox c = new ComboBox();
//c.setEditable(true);
primaryStage.setScene(new Scene(c));
primaryStage.show();
c.getItems().add("first");
c.getItems().add(null);
c.setConverter(new StringConverter<String>(){
@Override public String toString(String object) {
System.out.print("converting object: ");
if (object==null) {
System.out.println("null");
return "[none]";
}
System.out.println(object.toString());
return object.toString();
}
@Override public String fromString(String string) {
throw new RuntimeException("not required for non editable ComboBox");
}
});
}
}
這裏是輸出,你可以看到if (object==null)
語句的真正分支從不被調用。它是一個錯誤還是一個功能,是否可以自定義空值表示?
1.6.0_29-b11
2.2.3-b05
6.1
Windows 7
converting object: first
converting object: first
converting object: first
更新
加入(只是取消註釋):
c.setEditable(true);
我得到另一個行爲,那就是,點擊在組合選擇框中空項目,我得到的方法toString調用,但結果不會顯示在選擇框中。
+1:這似乎是在很多情況下,一個有效的解決方法。我已經測試過它,它的工作原理,但不是當comboBox是可編輯的。確切地說:提示文本在「選擇框」中顯示爲EVER,但當編輯組合框時它不顯示在「文本框區域」中。但是,我不能認爲這是對原始問題的迴應,因爲問題是關於可能的錯誤。我已經用更多的線索來更新問題了。 – AgostinoX
這就是我正在尋找的。謝謝。 –