How to disable JList selection in java?

Many times we need to disable the selection of items present in JList. For disabling the selection in JList we need to set default cell renderer to the JList with slight modification in it. DefaultListCellRenderer renders an item in a JList. It provides one method getListCellRendererComponent which has arguments such as list which is the JList which we are painting, value which is getElementAt value, index value of cell,
isSelected which is true when the item in a cell is selected.
cellHasFocus which is true when specified cell has focus.

If we keep isSelected and cellHasFocus as false then we can make the JList item as not selectable.

Lets see how we can achieve this :

String[] strList = {"Item 1", "Item 2", "Item 3"};
JList listEx = new JList(strList);
listEx.setCellRenderer(new DefaultListCellRenderer() {

public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, false, false);

return this;

In the above code as we can see we have made isSelected and cellHasFocus values are false, which disables the selection of items in JList.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment