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

发布于 2024-08-08 04:01:08 字数 32 浏览 1 评论 0原文

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

How can I change the background color of the item which is selected in JList dynamically?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

七分※倦醒 2024-08-15 04:01:08

像下面这样的东西应该有助于作为起点:

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());

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());
眼眸印温柔 2024-08-15 04:01:08

一种更简单的方法是进入 Eclipse 中的设计模式,然后在 JList 的属性中,单击带有两个小箭头且中间有一个黄色大箭头的按钮,以打开“显示高级属性”。然后向下滚动并更改“selectionBackground”处的颜色并更改那里的颜色(它可能是灰色的,但它仍然会改变)。现在,当您运行程序时,无论您选择什么,背景都将是该颜色。

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." 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). Now, when you run your program, whatever you select, the background will be that color.

佼人 2024-08-15 04:01:08
 jList1.setSelectedIndex(currentLine);
 jList1.setSelectionBackground(Color.red);

只需在循环中设置要着色的所有项目的选定索引并相应地更改颜色即可!

 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!

神爱温柔 2024-08-15 04:01:08

如果我清楚地理解你,请查看javax.swing.ListCellRenderer
您需要重新实现它或扩展 javax.swing.DefaultListCellRenderer 并自定义 getListCellRendererComponent 方法。

If I am clearly understanding you, look into javax.swing.ListCellRenderer.
You need to reimplement it or extend javax.swing.DefaultListCellRenderer and customize the getListCellRendererComponent method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文