JList keep heighlight after focus is lost

46 Views Asked by At

How to keep highlight (selected item) after focus on JList is lost.

setSelectedIndex didnt reselect the item after focus lost.

list.addFocusListener(new FocusListener() {
            @Override
            public void focusLost(FocusEvent var1) {
                if (index != -1) { 
                   list.setSelectedIndex(index); 
                }
            }
            @Override
            public void focusGained(FocusEvent var1) {}
            
        });

Solution:

public class SelectedListCellRenderer extends DefaultListCellRenderer {
        private static final long serialVersionUID = 1L;

        @Override
        public Component getListCellRendererComponent(JList<?> list, Object file, int index, boolean isSelected, boolean cellHasFocus) {
            if (index == lastIndex && lostFocus) {
                cellHasFocus = true;
            } 
            return super.getListCellRendererComponent(list, file, index, isSelected, cellHasFocus);
        }
    }

Then add it to JList:

list.setCellRenderer(new SelectedListCellRenderer());
list.addFocusListener(new FocusListener() {
                        @Override
                        public void focusLost(FocusEvent var1) {
                            if (lastIndex != -1) {
                                lostFocus = true;
                            }
                        } 
                        @Override
                        public void focusGained(FocusEvent var1) {
                            lostFocus = false;
                            repaint();
                        }
                    });
0

There are 0 best solutions below