Set the border in a JList in Java

9.3k views Asked by At

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?
        }
    }
 }
2

There are 2 answers

0
Paul Samsotha On BEST ANSWER

You can use a custom ListCellRender. Then in the if (isSelected) just add the border.

public class MyListCellRenderer implements ListCellRenderer{

    private final JLabel jlblCell = new JLabel(" ", JLabel.LEFT);
    Border lineBorder = BorderFactory.createLineBorder(Color.BLACK, 1);
    Border emptyBorder = BorderFactory.createEmptyBorder(2, 2, 2, 2);

    @Override
    public Component getListCellRendererComponent(JList jList, Object value, 
            int index, boolean isSelected, boolean cellHasFocus) {

        jlblCell.setOpaque(true);

        if (isSelected) {
            jlblCell.setForeground(jList.getSelectionForeground());
            jlblCell.setBackground(jList.getSelectionBackground());
            jlblCell.setBorder(new LineBorder(Color.BLUE));
        } else {
            jlblCell.setForeground(jList.getForeground());
            jlblCell.setBackground(jList.getBackground());
        }

        jlblCell.setBorder(cellHasFocus ? lineBorder : emptyBorder);

        return jlblCell;
    }
}

Then instantiate the render.

MyListCellRenderer renderer = new MyListCellRenderer();

JList list = new JList();
list.setCellRenderer(renderer);

The renderer will return a JLabel. So you can do anything you want to that label and that's what will appear in cell.

See ListCellRenderer javadoc

0
camickr On

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.