在JavaFX ComboBox中转换字符串

Pet*_*zov 5 javafx javafx-2 javafx-8

我试图用它来从自定义组合框中选择一个值:

import java.util.List;
import javafx.application.Application;
import static javafx.application.Application.launch;
import static javafx.application.Application.launch;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
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> listGroups = new ComboBox();

        listGroups.setButtonCell(new GroupListCell());
        listGroups.setCellFactory(new Callback<ListView<ListGroupsObj>, ListCell<ListGroupsObj>>()
        {
            @Override
            public ListCell<ListGroupsObj> call(ListView<ListGroupsObj> p)
            {
                return new GroupListCell();
            }
        });

        listGroups.setEditable(true);
        listGroups.setConverter..............

        // Insert Some data
        ListGroupsObj ob = ListGroupsObj.newInstance().groupId(12).groupName("Test");
        listGroups.getItems().addAll(ob);
        ListGroupsObj osb = ListGroupsObj.newInstance().groupId(13).groupName("Test2");
        listGroups.getItems().addAll(osb);
        listGroups.setValue(ob);

        // Display the selected Group
        listGroups.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ListGroupsObj>()
        {

            @Override
            public void changed(ObservableValue<? extends ListGroupsObj> arg0, ListGroupsObj arg1, ListGroupsObj arg2)
            {
                if (arg2 != null)
                {
                    System.out.println("Selected Group: " + arg1.getGroupId() + " - " + arg2.getGroupName());
                }
            }
        });

        final StackPane layout = new StackPane();
        layout.getChildren().add(listGroups);
        layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;");
        stage.setScene(new Scene(layout));
        stage.show();
    }

    class GroupListCell extends ListCell<ListGroupsObj>
    {
        @Override
        protected void updateItem(ListGroupsObj item, boolean empty)
        {
            super.updateItem(item, empty);
            if (item != null)
            {
                setText(item.getGroupId() + " - " + item.getGroupName());
            }
        }
    }

    private List<ListGroupsObj> listGroups;

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

    public class GroupConverter extends StringConverter<ListGroupsObj>
    {

        @Override
        public String toString(ListGroupsObj obj)
        {
            return obj.getGroupId() + " - " + obj.getGroupName();
        }

        @Override
        public ListGroupsObj fromString(String obj)
        {

            //TODO when you type for example "45 - NextGroup" you want to take only tyhe number"
            return ListGroupsObj.newInstance().groupName(obj);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

当我在comboBox之外单击时出现此错误:

Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: java.lang.String cannot be cast to com.selectmenuexample.MainApp$ListGroupsObj
Run Code Online (Sandbox Code Playgroud)

我发现可以使用转换器完成此操作,但是现在我知道如何使用它了。您可以协助实施吗?

Max*_*ela 4

这是错误的:

  • 您将 ComboBox 称为listGroups并将项目列表称为listGroups。因此,在您的起始代码中,您隐藏了该变量。所以我删除了那个无用的变量,因为您可以直接在组合框中操作项目。
  • 您基本上有三种方法/变量做完全相同的事情。将您的对象转换为字符串,并在它们之间使用“ - ”。所以我删除了GroupConverter和自定义cellFactory。您不需要它们,因为您的 ListGroupsObj 中已经有“ toString ()”方法来完成这项工作。

那么您误解了 ComboBox 的工作原理。如果它是可编辑的,则组合框将允许在文本字段内键入内容。这就是 StringConverter 的用武之地。它将允许您在 String 和 ListGroupsObj 之间进行转换以及周围的方式。

为了从 ListGroupsObj 转换为 String,只需在对象上调用“ toString ()”方法即可。

但反过来,您应该创建一个新的 ListGroupsObj,或者验证 ComboBox 中的内容是否已经不是您的一项。例如,如果您在组合框中选择一个项目,则将调用fromString() 。但是您不想创建新的 ListGroupsObj,您只想隔离项目列表中的 ListGroupsObj 并返回它。

现在,您可以保证对 ComboBox 上的getValue()的调用将始终返回 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) {
                //Here we try to identify if the given String actually represents one item of our list
                for(ListGroupsObj tempObj:comboBox.getItems()){
                    if(tempObj.toString().equals(obj)){
                        return tempObj;
                    }
                }
                //If not we just create a new one
                return ListGroupsObj.newInstance().groupName(obj);
            }
        });

        // Insert Some data
        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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

PS:该问题已在官方 JavaFX 问题跟踪器中提出,我将在此处保留链接,因为票证中还有另一个示例(需要登录): https: //javafx-jira.kenai.com/browse/RT- 29118