【发布时间】:2013-08-06 03:42:45
【问题描述】:
我使用 DefaultComboBoxModel 将特定项目添加到我的 JComboBox(字符串文本、图标图标)。但是出了点问题。当我将这两个项目添加到我的组合模型时,它看起来像这样:
ComboBoxWindow:
[icon ]
[icon value]
总之,我的组合框代码如下所示:
private JComboBox combobox;
...
DefaultComboBoxModel model = new DefaultComboBoxModel();
combobox = new JComboBox(model);
...
/*
* I use JButton for 'sending' hex value taken from JTextField to 'combobox'
* with help of 'addToComboBox()' method
*/
public void addToComboBox() {
String value = field.getText().toString(); // getin' text from 'left' JTextField
Color color = tcc.getColor(); // getin' color from some other JLabel
ColorSwatch icon = new ColorSwatch(10, true); // using some custom method to create little square icon
icon.setColor(color); // seting color of created icon
combobox.addItem(icon);
combobox.addItem(value);
}
我考虑过使用 ListCellRenderer,但我不知道如何“告诉”它应该同时使用“value”和“icon”来渲染 JLabel 组件。有可能通过使用 JButton 动态添加这些项目对我来说非常重要。
【问题讨论】:
-
动态添加项目到 JComboBox(已经可见)== MutableComboBoxModel
-
为了更好的帮助,请尽快发布SSCCE,简短,可运行,可编译,f.i. Icon you can take from JOptionPane
-
嗯,你通过
addItem()添加两个项目,所以你会得到两行......你的ColorSwatch类是否有一个toString()方法返回颜色十六进制代码? -
有关基本解决方法,请参阅 Oracle 教程如何使用组合框,提供自定义渲染器部分,关于 ListCellRenderer
-
哦!我知道!我将只发送图标颜色的十六进制值,在 ListCellRenderer 中我将使用 ColorSwatch 创建 JLabel 并发送十六进制值。毕竟要创建带有指定图标和文本的 JLabel,我只需要图标颜色的十六进制值:D 但问题是是否可以动态添加对象? : /
标签: java swing jcombobox listcellrenderer