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?`
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 JComboBo
x or a JTree
(because of the second element and its two children); even if it is not a JLis
t, 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:-
The border is thicker in some places and fine in others.
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:
Read more in tutorial .
EDIT: Just change LineBorder
to MatteBorder
(have changed code and image).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.