javafx-2组合框转换器:没有为null值调用方法toString(T对象)



在javafx2应用程序中,ComboBox应该显示一个项目列表,在本例中,为了简单起见,它们是String

这个列表包含一个null项目,因为我希望用户可以不做任何选择。

由于我正在使用ComboBox的converter属性,我想知道是否可以使用它为无选择的情况提供一个很好的表示,例如"[none]"而不是空行
但是我发现从来没有为null项调用过toString(Object对象)。

下面是重现案例的最短代码。包含版本信息。

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)语句的真正分支从未被调用。这是一个bug还是一个特性,还有可能自定义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);

我得到了另一种行为,即单击组合选择框中的null项,我得到了调用的方法toString,但结果没有显示在选择框中。

如果用户没有选择,可以使用setPromptText方法在comboBox中显示"[None]"。

样本代码:

comboBox.setValue(null);
comboBox.setPromptText("[None]");

最新更新