Java Swing: JList with ListCellRenderer selected item different height

前端 未结 7 1596
花落未央
花落未央 2020-12-17 05:27

I\'m making a custom ListCellRenderer. I know that you can have different dimensions for each individual cell. But now I want to have a different dimension for the selected

相关标签:
7条回答
  • 2020-12-17 05:58

    Thanks to Rastislav Komara I've been able to solve this quite easily:

    I've created an inner class that extends BasicListUI and created public method that is called on ListSelectionListener.valueChanged:

    private class MyRenderer implements ListCellRenderer {
        public int listSelectedIndex = -1;
    
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            if (index == listSelectedIndex)
                return new Yeah(isSelected);
            else
                return new Oh();
        }
    }
    MyRenderer lcr = new MyRenderer();
    private class MyListUI extends BasicListUI {
    
        public void triggerUpdate() {
            lcr.listSelectedIndex = list.getSelectedIndex();
            updateLayoutState();
            list.revalidate();
        }
    }
    

    The updateLayoutState method is normally triggered when the JList height changes. The only "insane" thing I'm doing here is that my renderer needs to know what the selected index is. This is because the updateLayoutState method doesn't use the selected index in it's height calculations. Somehow using list.getSelectedIndex() inside getListCellRendererComponent doesn't work well.

    Edit:
    Check also the anser by nevster and kleopatra, they look way smarter, try them first...

    0 讨论(0)
提交回复
热议问题