这是我的解决方案(可能有用)
/**
* A ComboBox with Enabling/disabling items support
*/
public class AvailableItemComboBox extends JComboBox {
private static final long serialVersionUID = 1L;
// previosly chosen item
protected int old = -1;
/**
* Default constructor
*/
public AvailableItemComboBox() {
super();
setRenderer(new EnabledJComboBoxRenderer());
initializeComboBox();
}
/**
* Constructor with model
*
* @param model
*/
public AvailableItemComboBox(ComboBoxModel model) {
super(model);
setRenderer(new EnabledJComboBoxRenderer());
initializeComboBox();
System.out.println("selected index is " + getSelectedIndex());
}
/**
* Constructor with data
*
* @param model
*/
public AvailableItemComboBox(Available[] items) {
super(items);
setRenderer(new EnabledJComboBoxRenderer());
initializeComboBox();
System.out.println("selected index is " + getSelectedIndex());
}
private void initializeComboBox() {
setSelectedIndex(findFirstAvailableItem());
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Listener called>>>>>>>>>>>>>>>>>>");
if (old != getSelectedIndex()) {
if (!((Available) getSelectedItem()).isEnabled()) {
setSelectedIndex(old);
} else {
old = getSelectedIndex();
}
}
}
});
}
// Finds first selecteditem and sets it as previous state
private int findFirstAvailableItem() {
int result = -1;
for (int index = 0; index < this.getItemCount(); index++) {
if (((Available)this.getItemAt(index)).isEnabled()) {
result = index;
break;
}
}
old = result;
return result;
}
}
public class EnabledJComboBoxRenderer extends BasicComboBoxRenderer {
private static final long serialVersionUID = 1L;
private Color disabledColor = Color.lightGray;
/**
* Constructs a new renderer for a JComboBox which enables/disables items
* based upon the parameter model.
*
* @param enabled
*/
public EnabledJComboBoxRenderer(){
super();
}
/**
* Sets the color to render disabled items.
*
* @param disabledColor
*/
public void setDisabledColor(Color disabledColor){
this.disabledColor = disabledColor;
}
/**
* Custom implementation to color items as enabled or disabled.
*
* @inheritDoc
*/
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
boolean enabled = ((Available) value).isEnabled();
if (!enabled) {
if (isSelected) {
c.setBackground(UIManager.getColor("ComboBox.background"));
} else {
c.setBackground(super.getBackground());
}
c.setForeground(disabledColor);
} else {
c.setBackground(super.getBackground());
c.setForeground(super.getForeground());
}
return c;
}
}
public interface Available {
public boolean isEnabled();
public void setEnabled(boolean enable);
}