我有一个JComboBox中填充了一些随机项目,可以在运行时更改。我已经使用getListCellRendererComponent(...)将它们设置为JLabels。我也设置了一些Jlabel为setEnabled(false)。检测选定的JComboBox项目是启用还是禁用
当用户从该JComboBox中选择一个项目时,有没有办法检测它是启用还是禁用?
我有一个JComboBox中填充了一些随机项目,可以在运行时更改。我已经使用getListCellRendererComponent(...)将它们设置为JLabels。我也设置了一些Jlabel为setEnabled(false)。检测选定的JComboBox项目是启用还是禁用
当用户从该JComboBox中选择一个项目时,有没有办法检测它是启用还是禁用?
renederer只是描绘它们,所以不会有isEnabled值来检查。而是使用与cellRenderer用来确定是否允许值的相同逻辑,当您查看选择时。或者可能从列表中删除这些值而不是禁用该值。
当然,如果您使用“相同的逻辑”,这意味着将其提取到方法中并调用该方法。 – 2011-04-10 13:20:34
使用相同的逻辑是我的替代解决方案。我希望会有另一种方式。 – Brad 2011-04-10 13:28:43
列表/组合(或任何集合组件)中的项目应该是具有某种状态的业务对象的表示。然后实现知道不同状态的渲染器,并使渲染器(渲染器)将状态映射为适当的视觉表示。
// the item
public class Valve {
private boolean open;
private boolean canOperate;
private Point location;
// getters and methods as appropriate
public boolean isOpen() { ...
...
}
// custom renderer
Component getListCellRendererComponent(....) {
// normal config, assuming you subclass DefaultListCellRender
super.getListCellRendererComponent(...)
if (value instanceof Valve) {
configFromValve((Valve) value)
}
return this;
}
private void configFromValve(Valve valve) {
setText("P: (" + valve.location().x + "," + valve.getLocation().y + ")");
setIcon(valve.isOpen() ? openIcon : closedIcon);
setEnabled(valve.canOperate());
}
也许我误解了你的描述,但是......决不会添加_components_作为项目。你不 - 你呢? – kleopatra 2011-04-10 13:38:17
@kleopatra:是的,我确实有这个问题吗?我需要放置图标+禁用某些项目。 – Brad 2011-04-10 14:10:45
问题在于混合不同的担忧(哪种摆动可以保持分离 - 这就是为什么有渲染器的原因;-)。看到我的答案,如何设计更多的摆动。 – kleopatra 2011-04-10 16:10:44