自定义ListCellRenderer不会改变背景颜色

发布于 2024-12-11 13:28:09 字数 655 浏览 0 评论 0原文

我有这样的课程:

 @SuppressWarnings("serial")
  private class DataCellRenderer extends JLabel implements ListCellRenderer 
  {
    public DataCellRenderer()
    {
      setHorizontalAlignment(SwingConstants.RIGHT); 
    }

    @Override
    public Component getListCellRendererComponent(
        JList list,
        Object value,
        int index,
        boolean isSelected,
        boolean cellHasFocus)
    {

      if(isSelected)
        setBackground(Color.red);

      setText("  " + value.toString());

      return this;
    }
  }

问题是当我在 JList 中选择一个单元格时,我的背景不会变成红色。 setText 部分有效,但我不明白为什么它不会改变单元格的背景颜色。大家有什么想法吗,谢谢!

I have this class:

 @SuppressWarnings("serial")
  private class DataCellRenderer extends JLabel implements ListCellRenderer 
  {
    public DataCellRenderer()
    {
      setHorizontalAlignment(SwingConstants.RIGHT); 
    }

    @Override
    public Component getListCellRendererComponent(
        JList list,
        Object value,
        int index,
        boolean isSelected,
        boolean cellHasFocus)
    {

      if(isSelected)
        setBackground(Color.red);

      setText("  " + value.toString());

      return this;
    }
  }

The problem is that my Background will not turn red when I select a cell in my JList. The setText part works but I can't figure out why it will not change my background color of the cell. Anyone have any ideas, Thanks!

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

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

发布评论

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

评论(3

深居我梦 2024-12-18 13:28:09

主要问题是标签默认是不透明的,因此您需要使标签不透明才能绘制背景。

但您不需要为此创建自定义渲染器。默认渲染器是不透明的。您需要做的就是设置列表的选择背景属性:

list.setSelectionBackground(Color.RED);

如果您尝试创建一个渲染器来右对齐文本,那么您只需在默认渲染器上设置一个属性:

DefaultListCellRenderer renderer = (DefaultListCellRenderer)list.getCellRenderer();
renderer.setHorizontalAlignment(SwingConstants.RIGHT);

The main problem is that labels are non-opaque by default, so you need to make the label opaque in order for the background to be painted.

But you don't need to create a custom renderer for this. The default renderer is opaque. All you need to do is set the selection background property of the list:

list.setSelectionBackground(Color.RED);

If you are trying to create a renderer to right align the text then you can just set a property on the default renderer:

DefaultListCellRenderer renderer = (DefaultListCellRenderer)list.getCellRenderer();
renderer.setHorizontalAlignment(SwingConstants.RIGHT);
千柳 2024-12-18 13:28:09

例如

在此处输入图像描述

import java.awt.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;

public class FilesInTheJList {

    private static final int COLUMNS = 5;
    private Dimension size;

    public FilesInTheJList() {
        final JList list = new JList(new File("C:\\").listFiles()) {

            private static final long serialVersionUID = 1L;

            @Override
            public Dimension getPreferredScrollableViewportSize() {
                if (size != null) {
                    return new Dimension(size);
                }
                return super.getPreferredScrollableViewportSize();
            }
        };
        list.setFixedCellHeight(50);
        list.setFixedCellWidth(150);
        size = list.getPreferredScrollableViewportSize();
        size.width *= COLUMNS;
        list.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        list.setCellRenderer(new MyCellRenderer());
        list.setVisibleRowCount(0);
        list.setLayoutOrientation(JList.HORIZONTAL_WRAP);

        JFrame f = new JFrame("Files In the JList");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new JScrollPane(list));
        f.pack();
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FilesInTheJList fITJL = new FilesInTheJList();
            }
        });
    }

    private static class MyCellRenderer extends JLabel implements ListCellRenderer {

        private static final long serialVersionUID = 1L;

        @Override
        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean cellHasFocus) {
            if (value instanceof File) {
                File file = (File) value;
                setText(file.getName());
                setIcon(FileSystemView.getFileSystemView().getSystemIcon(file));
                if (isSelected) {
                    setBackground(Color.red);
                    setForeground(Color.blue);
                } else {
                    setBackground(list.getBackground());
                    setForeground(list.getForeground());
                }
                //setPreferredSize(new Dimension(250, 25));
                //setEnabled(list.isEnabled());
                setFont(list.getFont());
                setOpaque(true);
            }
            return this;
        }
    }
}

for example

enter image description here

import java.awt.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;

public class FilesInTheJList {

    private static final int COLUMNS = 5;
    private Dimension size;

    public FilesInTheJList() {
        final JList list = new JList(new File("C:\\").listFiles()) {

            private static final long serialVersionUID = 1L;

            @Override
            public Dimension getPreferredScrollableViewportSize() {
                if (size != null) {
                    return new Dimension(size);
                }
                return super.getPreferredScrollableViewportSize();
            }
        };
        list.setFixedCellHeight(50);
        list.setFixedCellWidth(150);
        size = list.getPreferredScrollableViewportSize();
        size.width *= COLUMNS;
        list.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        list.setCellRenderer(new MyCellRenderer());
        list.setVisibleRowCount(0);
        list.setLayoutOrientation(JList.HORIZONTAL_WRAP);

        JFrame f = new JFrame("Files In the JList");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new JScrollPane(list));
        f.pack();
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FilesInTheJList fITJL = new FilesInTheJList();
            }
        });
    }

    private static class MyCellRenderer extends JLabel implements ListCellRenderer {

        private static final long serialVersionUID = 1L;

        @Override
        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean cellHasFocus) {
            if (value instanceof File) {
                File file = (File) value;
                setText(file.getName());
                setIcon(FileSystemView.getFileSystemView().getSystemIcon(file));
                if (isSelected) {
                    setBackground(Color.red);
                    setForeground(Color.blue);
                } else {
                    setBackground(list.getBackground());
                    setForeground(list.getForeground());
                }
                //setPreferredSize(new Dimension(250, 25));
                //setEnabled(list.isEnabled());
                setFont(list.getFont());
                setOpaque(true);
            }
            return this;
        }
    }
}
给我一枪 2024-12-18 13:28:09

默认情况下,JLabel 是透明的。如果你想让它显示背景,你需要:

label.setOpaque(true);

另外,你经常想要使用父列表的默认背景颜色,这将适合 UI 主题或列表本身的自定义:

if (isSelected) {
    label.setForeground(list.getSelectionForeground());
    label.setBackground(list.getSelectionBackground());
} else {
    label.setForeground(list.getForeground());
    label.setBackground(list.getBackground());
}

将它们放在一起:

import javax.swing.*;
import java.awt.*;

public class CustomListCellRenderer implements ListCellRenderer<MyObject>
{
    @Override
    public Component getListCellRendererComponent(JList<? extends MyObject> list,
                                                  MyObject value,
                                                  int index,
                                                  boolean isSelected,
                                                  boolean cellHasFocus)
    {
        JLabel label = new JLabel();
        label.setOpaque(true);
        label.setText(value.getName());
        if (isSelected) {
            label.setForeground(list.getSelectionForeground());
            label.setBackground(list.getSelectionBackground());
        } else {
            label.setForeground(list.getForeground());
            label.setBackground(list.getBackground());
        }
        return label;
    }
}

By default JLabel is transparent. If you want it to show a background, you need:

label.setOpaque(true);

Also, you often want to use the default background colour of the parent list, which will fit with the UI theme or customisation of the list itself:

if (isSelected) {
    label.setForeground(list.getSelectionForeground());
    label.setBackground(list.getSelectionBackground());
} else {
    label.setForeground(list.getForeground());
    label.setBackground(list.getBackground());
}

Putting it all together:

import javax.swing.*;
import java.awt.*;

public class CustomListCellRenderer implements ListCellRenderer<MyObject>
{
    @Override
    public Component getListCellRendererComponent(JList<? extends MyObject> list,
                                                  MyObject value,
                                                  int index,
                                                  boolean isSelected,
                                                  boolean cellHasFocus)
    {
        JLabel label = new JLabel();
        label.setOpaque(true);
        label.setText(value.getName());
        if (isSelected) {
            label.setForeground(list.getSelectionForeground());
            label.setBackground(list.getSelectionBackground());
        } else {
            label.setForeground(list.getForeground());
            label.setBackground(list.getBackground());
        }
        return label;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文