有没有办法将对象添加到JComboBox并分配要显示的字符串?

时间:2021-10-27 11:31:30

I want to add objects to a JComboBox but show a String on the JComboBox for each object.

我想将对象添加到JComboBox,但在JComboBox上为每个对象显示一个String。

For example, in the following html code

例如,在以下html代码中

<select>
  <option value="1">Item 1</option>
  <option value="2">Item 2</option>
  <option value="3">Item 3</option>
  <option value="4">Item 4</option>
</select>

in the first item, the String that is shown is "Item 1", but the value of the item is "1".

在第一项中,显示的字符串是“项目1”,但项目的值是“1”。

Is there a form to do something like that with a JComboBox?

是否有表格可以使用JComboBox执行此类操作?

4 个解决方案

#1


2  

Start by taking a look at How to Use Combo Boxes, in particular Providing a Custom Renderer

首先来看看如何使用组合框,特别是提供自定义渲染器

Basically, you want to define your object which will be contained within the combo box...

基本上,你想要定义你的对象,它将包含在组合框中......

public class MyObject {
    private String name;
    private int value;

    public MyObject(String name, int value) {
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public int getValue() {
        return value;
    }
}

Then create a custom ListCellRenderer that knows how to renderer it...

然后创建一个知道如何渲染它的自定义ListCellRenderer ...

public class MyObjectListCellRenderer extends DefaultListCellRenderer {

    public Component getListCellRendererComponent(
                                   JList list,
                                   Object value,
                                   int index,
                                   boolean isSelected,
                                   boolean cellHasFocus) {
        if (value instanceof MyObject) {
            value = ((MyObject)value).getName();
        }
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        return this;
    }
}

Then populate you combo box and apply the cell renderer...

然后填充组合框并应用单元格渲染器...

JComboBox box = new JComboBox();
box.addItem(new MyObject(..., ...));
//...
box.setRenderer(new MyObjectListCellRenderer());

You could, equally, override the toString method of your object, but I tend to like to avoid this for display purposes, as I like the toString method to provide diagnostic information about the object, but that's me

同样,您可以覆盖对象的toString方法,但我倾向于为了显示目的而避免这种情况,因为我喜欢使用toString方法来提供有关对象的诊断信息,但那就是我

#2


1  

If your combo box model contains objects, their toString() method will be used by default to display them in the combo box. If the toString() method displays what you want, you don't have anything to do.

如果组合框模型包含对象,则默认情况下将使用其toString()方法在组合框中显示它们。如果toString()方法显示您想要的内容,则无需执行任何操作。

Otherwise, you just need to set a cell renderer to customize the way each object is displayed (and that doesn't limit you to text: you can also change the font, color, icon, etc.).

否则,您只需要设置一个单元格渲染器来自定义每个对象的显示方式(这不会限制您使用文本:您还可以更改字体,颜色,图标等)。

This is all described in the Swing tutorial.

这些都在Swing教程中描述。

#3


0  

Yes, that can be done using the object type as the parameter for the JComboBox generic, like this:

是的,可以使用对象类型作为JComboBox泛型的参数来完成,如下所示:

public class TestFrame extends JFrame {
    // This will be the JComboBox's item class
    private static class Test {
        private Integer value;
        private String label;

        public Test(Integer value, String label) {
            this.setValue(value);
            this.setLabel(label);
        }

        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public String getLabel() {
            return label;
        }

        public void setLabel(String label) {
            this.label = label;
        }

        // The "toString" method will be used by the JComboBox to generate the label for the item
        @Override
        public String toString() {
            return getLabel();
        }        
    }

    public static void main(String[] args) {
        TestFrame frmMain = new TestFrame();
        frmMain.setSize(300, 50);
        frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Here you declare a JComboBox that 
        // uses the type "Test" for item elements 
        JComboBox<Test> cmbCombo = new JComboBox<TestFrame.Test>();

        for (int i = 0; i < 10; i++) {
            // Add some elements for the combo 
            cmbCombo.addItem(new Test(i, String.format("This is the item %d", i + 1)));
        }

        // Listen to changes in the selection
        cmbCombo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JComboBox<Test> cmbCombo = (JComboBox<Test>) e.getSource();

                // The selected element is a "Test" instance, just cast it to the correct type
                Test test = (Test) cmbCombo.getSelectedItem();

                // Manipulate the selected object at will
                System.out.printf("The selected value is '%d'\n", test.getValue());
            }
        });

        frmMain.add(cmbCombo);
        frmMain.setVisible(true);
    }
}

#4


0  

For example, in the following html code

例如,在以下html代码中

For something simple like this, where you have an "ID", "Value" type of data, I do like the approach of a custom Object who's purpose in life is to provide a custom toString() method. See Combo Box With Hidden Data for such an reusable object.

对于像这样简单的东西,你有一个“ID”,“值”类型的数据,我喜欢自定义对象的方法,他们的目的是提供一个自定义的toString()方法。有关此类可重用对象,请参阅带有隐藏数据的组合框。

Many people in the forums do recommend a custom renderer. Unfortunately using a custom renderer breaks the default functionality of the comobo box. See Combo Box With Custom Renderer for more information as a solution.

论坛中的许多人都推荐自定义渲染器。不幸的是,使用自定义渲染器会破坏comobo框的默认功能。有关详细信息,请参阅带有自定义渲染器的组合框。

#1


2  

Start by taking a look at How to Use Combo Boxes, in particular Providing a Custom Renderer

首先来看看如何使用组合框,特别是提供自定义渲染器

Basically, you want to define your object which will be contained within the combo box...

基本上,你想要定义你的对象,它将包含在组合框中......

public class MyObject {
    private String name;
    private int value;

    public MyObject(String name, int value) {
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public int getValue() {
        return value;
    }
}

Then create a custom ListCellRenderer that knows how to renderer it...

然后创建一个知道如何渲染它的自定义ListCellRenderer ...

public class MyObjectListCellRenderer extends DefaultListCellRenderer {

    public Component getListCellRendererComponent(
                                   JList list,
                                   Object value,
                                   int index,
                                   boolean isSelected,
                                   boolean cellHasFocus) {
        if (value instanceof MyObject) {
            value = ((MyObject)value).getName();
        }
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        return this;
    }
}

Then populate you combo box and apply the cell renderer...

然后填充组合框并应用单元格渲染器...

JComboBox box = new JComboBox();
box.addItem(new MyObject(..., ...));
//...
box.setRenderer(new MyObjectListCellRenderer());

You could, equally, override the toString method of your object, but I tend to like to avoid this for display purposes, as I like the toString method to provide diagnostic information about the object, but that's me

同样,您可以覆盖对象的toString方法,但我倾向于为了显示目的而避免这种情况,因为我喜欢使用toString方法来提供有关对象的诊断信息,但那就是我

#2


1  

If your combo box model contains objects, their toString() method will be used by default to display them in the combo box. If the toString() method displays what you want, you don't have anything to do.

如果组合框模型包含对象,则默认情况下将使用其toString()方法在组合框中显示它们。如果toString()方法显示您想要的内容,则无需执行任何操作。

Otherwise, you just need to set a cell renderer to customize the way each object is displayed (and that doesn't limit you to text: you can also change the font, color, icon, etc.).

否则,您只需要设置一个单元格渲染器来自定义每个对象的显示方式(这不会限制您使用文本:您还可以更改字体,颜色,图标等)。

This is all described in the Swing tutorial.

这些都在Swing教程中描述。

#3


0  

Yes, that can be done using the object type as the parameter for the JComboBox generic, like this:

是的,可以使用对象类型作为JComboBox泛型的参数来完成,如下所示:

public class TestFrame extends JFrame {
    // This will be the JComboBox's item class
    private static class Test {
        private Integer value;
        private String label;

        public Test(Integer value, String label) {
            this.setValue(value);
            this.setLabel(label);
        }

        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public String getLabel() {
            return label;
        }

        public void setLabel(String label) {
            this.label = label;
        }

        // The "toString" method will be used by the JComboBox to generate the label for the item
        @Override
        public String toString() {
            return getLabel();
        }        
    }

    public static void main(String[] args) {
        TestFrame frmMain = new TestFrame();
        frmMain.setSize(300, 50);
        frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Here you declare a JComboBox that 
        // uses the type "Test" for item elements 
        JComboBox<Test> cmbCombo = new JComboBox<TestFrame.Test>();

        for (int i = 0; i < 10; i++) {
            // Add some elements for the combo 
            cmbCombo.addItem(new Test(i, String.format("This is the item %d", i + 1)));
        }

        // Listen to changes in the selection
        cmbCombo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JComboBox<Test> cmbCombo = (JComboBox<Test>) e.getSource();

                // The selected element is a "Test" instance, just cast it to the correct type
                Test test = (Test) cmbCombo.getSelectedItem();

                // Manipulate the selected object at will
                System.out.printf("The selected value is '%d'\n", test.getValue());
            }
        });

        frmMain.add(cmbCombo);
        frmMain.setVisible(true);
    }
}

#4


0  

For example, in the following html code

例如,在以下html代码中

For something simple like this, where you have an "ID", "Value" type of data, I do like the approach of a custom Object who's purpose in life is to provide a custom toString() method. See Combo Box With Hidden Data for such an reusable object.

对于像这样简单的东西,你有一个“ID”,“值”类型的数据,我喜欢自定义对象的方法,他们的目的是提供一个自定义的toString()方法。有关此类可重用对象,请参阅带有隐藏数据的组合框。

Many people in the forums do recommend a custom renderer. Unfortunately using a custom renderer breaks the default functionality of the comobo box. See Combo Box With Custom Renderer for more information as a solution.

论坛中的许多人都推荐自定义渲染器。不幸的是,使用自定义渲染器会破坏comobo框的默认功能。有关详细信息,请参阅带有自定义渲染器的组合框。