Skip to main content

Posts

Showing posts from March, 2011

JComboBox with Disabled Items

Recently, I was working on a project in Java and needed to have a combo box, but with certain items in the list disabled (e.g. gray and non-selectable). At first, I simply set a custom renderer for the combo box which checked if the item was disabled. That, however, did not prevent the items from being selected. Thus, I set about to find a viable solution. There are plenty of solutions out there, but none seemed to work exactly the way I wanted. In the end, I ended up subclassing JComboBox to provide the functionality of disabling individual items. Here is my result, in under 100 lines: import java.awt.Component; import java.util.ArrayList; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.plaf.basic.BasicComboBoxRenderer; public class PartialDisableComboBox extends JComboBox { private static final long serialVersionUID = -1690671707274328126L; private ArrayList<boolean> itemsState = new ArrayList<boolean>(); public PartialDisableComboBox