Here's what's wrong:
- You invoked the combobox group listGroups and the list of listGroups elements . So, in your startup code, you were hiding this variable. Therefore, I deleted this useless variable, since you can manipulate elements directly in ComboBox.
- /, . " -" . GroupConverter cellFactory. , toString() ListGroupsObj, .
, ComboBox. , ComboBox - TextField. , StringConverter. ListGroupsObj .
ListGroupsObj String, toString() .
ListGroupsObj, , ComboBox . , comboBox, fromString(). ListGroupsObj, ListGroupsObj .
, getValue() ComboBox ListGroupsObj, StringConverter.
:
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class MainApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
final ComboBox<ListGroupsObj> comboBox = new ComboBox();
comboBox.setEditable(true);
comboBox.setConverter(new StringConverter<ListGroupsObj>() {
@Override
public String toString(ListGroupsObj obj) {
return obj.toString();
}
@Override
public ListGroupsObj fromString(String obj) {
for(ListGroupsObj tempObj:comboBox.getItems()){
if(tempObj.toString().equals(obj)){
return tempObj;
}
}
return ListGroupsObj.newInstance().groupName(obj);
}
});
ListGroupsObj ob = ListGroupsObj.newInstance().groupId(12).groupName("Test");
comboBox.getItems().addAll(ob);
ListGroupsObj osb = ListGroupsObj.newInstance().groupId(13).groupName("Test2");
comboBox.getItems().addAll(osb);
comboBox.setValue(ob);
final StackPane layout = new StackPane();
layout.getChildren().add(comboBox);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;");
stage.setScene(new Scene(layout));
stage.show();
}
public static class ListGroupsObj {
private int groupId;
private String groupName;
public static ListGroupsObj newInstance() {
return new ListGroupsObj();
}
public ListGroupsObj() {
}
public ListGroupsObj groupId(int groupId) {
this.groupId = groupId;
return this;
}
public ListGroupsObj groupName(String groupName) {
this.groupName = groupName;
return this;
}
public int getGroupId() {
return groupId;
}
public String getGroupName() {
return groupName;
}
@Override
public String toString() {
return groupId + " - " + groupName;
}
}
}
PS: JavaFX Tracker, , ( ): https://javafx-jira.kenai.com/browse/RT-29118