Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable items in JList

Tags:

java

swing

jlist

I'm using a JList as part of a wizard to display all the steps to be performed (it also allows clicking on a step to go to it). Some steps will not always be needed, based on what's done in previous steps. It's these inapplicable steps I'd like to disable in the list.

How can I go about disabling (preventing the selection of) certain items in the list? Is there a better way than subclassing JList and overriding every selection-related method?

like image 871
Brad Mace Avatar asked Dec 01 '11 16:12

Brad Mace


1 Answers

I wanted a JList with cells that couldn't be select AND were transparent. So here's what I did:

class DisabledItemListCellRenderer extends JLabel implements ListCellRenderer<Object> {

    private static final long serialVersionUID = 1L;

    public DisabledItemListCellRenderer() {
        setOpaque(false);
    }

    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {
        String txt = (String) value;
        setText(txt);

        return this;
    }       
}
like image 64
Sean Ford Avatar answered Oct 02 '22 13:10

Sean Ford