我的代码动态创建 Jcombobox
并填充查询结果中的项目。
此查询返回一个包含标签和值的对象。
我想在调用 combo.getSelectedItem()
时显示标签并返回值。
我看到了这个Example
在搜索时,但我没有得到这个想法。
JComboBox<String> jComboBox=new JComboBox<String>();
if(dataSourceAttributeObjs!=null && dataSourceAttributeObjs.size()>0)
{
jComboBox.addItem("Select");
for(DataSourceAttributeObj dataSourceAttributeObj:dataSourceAttributeObjs)
{
jComboBox.addItem(dataSourceAttributeObj.getLabel());
}
}
最佳答案
您提到的示例( Set Value and Label to JComboBox )描述了为组合框定义自定义渲染器的可能性,这似乎是您的情况的正确方法。
nachokk的回答在一段代码中:
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class CustomComboBoxRenderer {
public static void main(final String[] arguments) {
new CustomComboBoxRenderer().launchGui();
}
private void launchGui() {
final JFrame frame = new JFrame("Stack Overflow: custom combo box renderer");
frame.setBounds(100, 100, 800, 600);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final JComboBox<Concept> comboBox = getComboBox();
final JLabel label = new JLabel("Please make a selection...");
comboBox.addActionListener(actionEvent -> {
final Object selectedItem = comboBox.getSelectedItem();
if (selectedItem instanceof Concept)
label.setText(((Concept) selectedItem).getValue());
});
final JPanel panel = new JPanel(new BorderLayout());
panel.add(comboBox, BorderLayout.NORTH);
panel.add(label, BorderLayout.CENTER);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
private JComboBox<Concept> getComboBox() {
final List<Concept> concepts = Arrays.asList(new Concept("label 1", "value 1"),
new Concept("label 2", "value 2"),
new Concept("label 3", "value 3"));
final JComboBox<Concept> comboBox = new JComboBox<>(new Vector<>(concepts));
comboBox.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(final JList<?> list,
final Object value,
final int index,
final boolean isSelected,
final boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
if (value instanceof Concept)
setText(((Concept) value).getLabel());
return this;
}
});
return comboBox;
}
}
Concept
类可能如下所示:
public class Concept {
private final String label;
private final String value;
public Concept(String label, String value) {
this.label = label;
this.value = value;
}
public String getLabel() {
return label;
}
public String getValue() {
return value;
}
}
关于java - 如何在 Swing 中将 Label 设置为 Display,将 value 设置为 JCombobox 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30588102/