简体   繁体   English

如何动态更改JList中所选项的背景颜色

[英]How to change background color of the selected item in JList dynamically

如何动态更改在JList中选择的项目的背景颜色?

Something like the following should help as a starting point: 以下内容应该有助于作为一个起点:

public class SelectedListCellRenderer extends DefaultListCellRenderer {
     @Override
     public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
         Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
         if (isSelected) {
             c.setBackground(Color.RED);
         }
         return c;
     }
}
// During the JList initialisation...
jlist1.setCellRenderer(new SelectedListCellRenderer());
 jList1.setSelectedIndex(currentLine);
 jList1.setSelectionBackground(Color.red);

Just Set Selected index of all the items you want to color in a loop and Change the color Accordingly! 只需设置要在循环中着色的所有项目的选定索引并更改颜色相应!

An easier way would be to go to design mode in Eclipse, and in the properties of your JList, click on the button that has two small arrows with a big yellow arrow inbetween to open up "show advanced properties." 更简单的方法是在Eclipse中进入设计模式,在JList的属性中,单击具有两个小箭头的按钮,中间有一个大的黄色箭头,以打开“显示高级属性”。 then scroll down and change the color where it says "selectionBackground" and change the color there (it will probably be gray, but it will still change). 然后向下滚动并更改其中显示“selectionBackground”的颜色并更改其中的颜色(它可能是灰色的,但它仍然会改变)。 Now, when you run your program, whatever you select, the background will be that color. 现在,当您运行程序时,无论您选择什么,背景都将是该颜色。

If I am clearly understanding you, look into javax.swing.ListCellRenderer . 如果我清楚地了解你,请查看javax.swing.ListCellRenderer You need to reimplement it or extend javax.swing.DefaultListCellRenderer and customize the getListCellRendererComponent method. 您需要重新实现它或扩展javax.swing.DefaultListCellRenderer并自定义getListCellRendererComponent方法。

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

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