AgostinoX
AgostinoX

Reputation: 7683

javafx-2 ComboBox converter: method toString(T object) not called for null values

In a javafx2 application, a ComboBox should present a list of items, in the example they are String s for simplicity.

This list contains a null item, since i want the user to be allowed to make no choice.

Since I was playing with the converter property of the ComboBox, I wondered if I could use it to provide a nice representation for the no-choice case, for example "[none]" instead of an empty line.
But i've discovered that the toString(Object object) is never called for the null item.

Here follows the shortest code that reproduces the case. Version information included.

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");
        }

    });

}

}

And here it's the output, as you can see the true branch of the if (object==null) statement is never called. Is it a bug or a feature, and is it yet possible to customize null representation?

 1.6.0_29-b11
 2.2.3-b05
 6.1
 Windows 7
 converting object: first
 converting object: first
 converting object: first

update
Adding a (just uncomment it):

c.setEditable(true);

I get another behavior, that is, clicking on the null item in the combo selection box, I get the method toString called, but the result is not presented in the selection box.

Upvotes: 1

Views: 5872

Answers (1)

invariant
invariant

Reputation: 8900

you can use setPromptText method to display "[None]" in comboBox if user make no choice.

Sample Code :

comboBox.setValue(null);

comboBox.setPromptText("[None]");

Upvotes: 4

Related Questions