简体   繁体   English

在Java中的JList中设置边框

[英]Set the border in a JList in Java

I have a JList in Java. 我在Java中有一个JList。 Whenever the user clicks on an element, I would like to add a specific borderLine in that element. 每当用户点击一个元素时,我想在该元素中添加一个特定的borderLine。 Is that possible? 那可能吗?

I have the following code in Java: 我在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?
        }
    }
 }

Create a custom renderer for the list and add a Border to the item that is selected. 为列表创建自定义渲染器,并将Border添加到所选项目。

Read the section from the Swing tutorial on How to Use Lists for more information and examples. 有关更多信息和示例,请阅读有关如何使用列表的Swing教程中的部分。

You can use a custom ListCellRender . 您可以使用自定义ListCellRender Then in the if (isSelected) just add the border. 然后在if (isSelected)添加边框。

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. 渲染器将​​返回JLabel。 So you can do anything you want to that label and that's what will appear in cell. 所以你可以做任何你想要的标签,这就是单元格中出现的内容。

See ListCellRenderer javadoc 请参阅ListCellRenderer javadoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM