Java 有没有办法将对象添加到 JComboBox 并分配一个要显示的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20155122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any way to add objects to a JComboBox and assign a String to be shown?
提问by Adrian
I want to add objects to a JComboBox but show a String on the JComboBox for each object.
我想将对象添加到 JComboBox 但在 JComboBox 上为每个对象显示一个字符串。
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".
在第一项中,显示的字符串是“Item 1”,但该项的值为“1”。
Is there a form to do something like that with a JComboBox?
有没有一种表格可以用 JComboBox 做类似的事情?
回答by JB Nizet
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 教程中进行了描述。
回答by higuaro
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);
}
}
回答by MadProgrammer
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
提供有关对象的诊断信息的方法,但这就是我
回答by camickr
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 Datafor 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 Rendererfor more information as a solution.
论坛中的许多人确实推荐了自定义渲染器。不幸的是,使用自定义渲染器破坏了组合框的默认功能。有关作为解决方案的更多信息,请参阅带有自定义渲染器的组合框。