java - 如何为 JCombobox 中的线条制作独特的字体颜色?

标签 java swing jcombobox

我想为 JCombobox 中的行/条目设置字体颜色,每一行都是唯一的。所以基本上当你点击下拉箭头时,你应该看到几条不同颜色的线,我想根据它们的属性自己指定颜色。我应该怎么做呢?谢谢!

最佳答案

您需要这样创建自定义 ListCellRenderer:

class Renderer extends JLabel implements ListCellRenderer {

并实现这个方法:

public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {
        // Get the selected index. (The index param isn't
        // always valid, so just use the value.)

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

        // Display the text
        String text = (String) value;
        setText(text);

        // Get the source

然后,根据您的来源,使用 this.setForeground(Color color) 设置文本的颜色。最后,

return this;

关于java - 如何为 JCombobox 中的线条制作独特的字体颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/935286/

相关文章:

java - java中的线程不工作

java - JComboBox 不更新所选项目/内部类访问

Java JFrame 意外地奇怪地删除组件

java - 将 Action 监听器添加到 JComboBox

java - Sqlite 日期时间类型问题

java - 创建 JPA 提供程序

java - 摆脱太多的如果。什么是更好的方法?

java - 设计循环的更好方法

java - 无法在单个 jframe 中的卡片布局中切换卡片

java - 双重打印JList