【发布时间】:2019-10-01 11:56:45
【问题描述】:
我很难制作一个用于过滤和选择从内部数据结构中提取的特定自定义数据对象的 JComboBox,而 JComboBox 中显示的值将只是该自定义中一个字段的值数据对象,甚至是封闭自定义数据对象的字段字段(即自定义对象本身)。例如,我有设备型号注册表。
https://drive.google.com/open?id=1q-_ii_V7SWDBFvUJGw0cd2BEWP3BnM0H
模型具有定义它的名称、规格、设备类型和制造商。这是我使用的实际模型类:
public class Models
{
private DeviceTypes deviceType;
private Manufacturers manufacturer;
private String name;
//getters and setters
}
这是包含所有模型及其 ID 的 HashMap 的进一步部分。
public Map<Integer,Models> modelsTable = new HashMap<Integer, Models>();
我希望能够在 JComboBox 中添加和删除项目,并选择与 JComboBox 项目对应的实际数据以使用这些对象创建新模型。 执行此操作的标准方法是什么?我创建了一个 ComboBox 渲染器:
public class DeviceTypeRenderer extends BasicComboBoxRenderer
{
private static final long serialVersionUID = 3442865560696889757L;
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
if (value instanceof DeviceTypes)
{
value = ((DeviceTypes)value).getName();
}
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
return this;
}
}
public class ManufacturersRenderer extends BasicComboBoxRenderer
{
private static final long serialVersionUID = 3723328665061573656L;
public Component getListCellRendererComponent(JList<?> list, Object value,int index, boolean isSelected, boolean cellHasFocus)
{
if (value instanceof Manufacturers)
{
value = ((Manufacturers)value).getName();
}
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
return this;
}
}
然后我只是将它们作为数据对象添加或删除。
DeviceTypes deviceType = new DeviceTypes(name,description);
comboBoxDeviceType.addItem(deviceType);
而 JComboBox 显示 deviceType.getName();
什么是最好的方法来做相反的事情。要获得一个实际的数据类表单 JComboBox 项目选择?我可能以错误的方式做这一切,并且使用了很多不好的做法。如果您看到,请通知我更正自己,如果您能告诉我如何正确实施,我将不胜感激。提前谢谢!
【问题讨论】:
标签: java swing data-structures jcombobox