Set the border in a JList in Java

programmer picture programmer · Dec 29, 2013 · Viewed 8.3k times · Source

I have a JList in Java. Whenever the user clicks on an element, I would like to add a specific borderLine in that element. Is that possible?

I have the following code in Java:

DefaultListModel listModel = new DefaultListModel();
listModel.addElement("element1");
listModel.addElement("element2");
listModel.addElement("element3");
list = new JList(listModel);
list.addListSelectionListener(this);

For the listener i have:

 public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting() == false) {
        if (list.getSelectedIndex() == -1) {
             ;
    } else {    
       CurrentIndex = list.getSelectedIndex();
       //set Current's Index border, how can i do that?
        }
    }
 }

Answer

camickr picture camickr · Dec 29, 2013

Create a custom renderer for the list and add a Border to the item that is selected.

Read the section from the Swing tutorial on How to Use Lists for more information and examples.