Pregunta

This is an example of a JList. I know how to set a border to the entire JList or the panel containing the JList. My question is that how can we create line borders between the cells?`

enter image description here

For example in the given picture the color of the line border between the first cell and the second is grey, while there is a white colored line border between all the other cells.

Please don't say that this is a JComboBox or a JTree (because of the second element and its two children); even if it is not a JList, I want my JList to have similar LineBorders between the cells.


My web search led me to this interface. Its method getListCellRendererComponent takes arguments like E value, int index, boolean isSelected, boolean cellHasFocus, while I want the LineBorder to appear between all the cells no matter what index they have and whether they are selected or not etc.


EDIT:-

enter image description here

The border is thicker in some places and fine in others.

¿Fue útil?

Solución

You can achive that with help of ListCellRenderer. Here is simple example:

import java.awt.Color;
import java.awt.Component;

import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;


public class TestFrame extends JFrame{

    public TestFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        init();
        pack();
        setVisible(true);
    }

    private void init() {
        JList<String> list = new JList<>(new String[]{"1","2","3"});
        list.setCellRenderer(getRenderer());
        add(list);
    }

    private ListCellRenderer<? super String> getRenderer() {
        return new DefaultListCellRenderer(){
            @Override
            public Component getListCellRendererComponent(JList<?> list,
                    Object value, int index, boolean isSelected,
                    boolean cellHasFocus) {
                JLabel listCellRendererComponent = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected,cellHasFocus);
                listCellRendererComponent.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0,Color.BLACK));
                return listCellRendererComponent;
            }
        };
    }

    public static void main(String... strings) {
        new TestFrame();
    }
}

Looks like:

enter image description here

Read more in tutorial.

EDIT: Just change LineBorder to MatteBorder(have changed code and image).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top