JList:如何获得位于“之间"的LineBorder.细胞? [英] JList: How to get a LineBorder "between" cells?
问题描述
这是JList的示例.我知道如何为整个JList或包含JList的面板设置边框. 我的问题是,我们如何在单元格之间创建线条边界?
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.
请不要说这是JComboBo
x或JTree
(因为第二个元素及其两个子元素);即使它不是JLis
t,我也希望我的JList
在cells
之间具有相似的LineBorders
.
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.
-
边界在某些地方较粗,而在其他地方则很好.
The border is thicker in some places and fine in others.
推荐答案
您可以在ListCellRenderer
的帮助下实现这一目标.这是简单的示例:
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();
}
}
看起来像:
在教程中了解更多.
只需将LineBorder
更改为MatteBorder
(已更改代码和图像).
Just change LineBorder
to MatteBorder
(have changed code and image).
这篇关于JList:如何获得位于“之间"的LineBorder.细胞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!