【问题标题】:Is it possible to have a different font colors on one JLabel inside in the JList?是否可以在 JList 中的一个 JLabel 上使用不同的字体颜色?
【发布时间】:2011-11-12 16:17:11
【问题描述】:

我的 Jlist 中有一个单词列表,每个单词旁边都有它们的定义。我希望单词的字体具有与其定义不同的颜色。我的问题是,是否可以在一个 Jlist 中有两种不同的颜色?

我必须使用 ListCellRenderer 吗?

谢谢...

【问题讨论】:

  • 是的,但是DefaultListCellRendererJLabel,可以使用HTML。
  • 仍未阅读或不理解渲染器教程?答案不会改变,但您经常会问“我必须使用 ListCellRenderer”吗 - 它是并且永远都是响亮的 YES
  • 无论如何,您对@Thomas 在stackoverflow.com/questions/7331388/… 中的回答到底是什么不理解?他已经给了你两个选择……
  • @kleopatra 现在可以使用了。谢谢 ;-)
  • @kleopatra 实际上我使用了一种方法,这就是为什么它需要时间来工作.. 但现在可以了。 ;-)

标签: java swing intellij-idea listcellrenderer


【解决方案1】:

我想你可以使用"<html>" 风格。它可能看起来有些奇怪,但如果您以 "<html>"(不是大写字母 HTML)开始您的文本(字符串值),您将能够在标签上使用 html 代码。

举个例子;

new JLabel("<html><font color=red>RED</font> - <font color=navy>Navy</font></html>");

与 JList 类似。

【讨论】:

    【解决方案2】:
    Is it possible to have a two different colors in one Jlist? 
    

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    
    public class JListDisabledItemDemo implements ItemListener, Runnable {
    
        private JFrame f = new JFrame("Colors");
        private static final String ITEMS[] = {" black ", " blue ", " green ",
            " orange ", " purple ", " red ", " white ", " yellow "};
        private JList jList;
        private JCheckBox[] checkBoxes;
        private boolean[] enabledFlags;
    
        @Override
        public void run() {
            JPanel pnlEnablers = new JPanel(new GridLayout(0, 1));
            pnlEnablers.setBorder(BorderFactory.createTitledBorder("Enabled Items"));
            checkBoxes = new JCheckBox[ITEMS.length];
            enabledFlags = new boolean[ITEMS.length];
            for (int i = 0; i < ITEMS.length; i++) {
                checkBoxes[i] = new JCheckBox(ITEMS[i]);
                checkBoxes[i].setSelected(true);
                checkBoxes[i].addItemListener(this);
                enabledFlags[i] = true;
                pnlEnablers.add(checkBoxes[i]);
            }
            jList = new JList(ITEMS);
            jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            jList.setSelectionModel(new DisabledItemSelectionModel());
            jList.setCellRenderer(new DisabledItemListCellRenderer());
            jList.addListSelectionListener(new ListSelectionListener() {
    
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (!e.getValueIsAdjusting()) {
                        System.out.println("selection");
                    }
                }
            });
            JScrollPane scroll = new JScrollPane(jList);
            scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    
            Container contentPane = f.getContentPane();
            contentPane.setLayout(new GridLayout(1, 2));
            contentPane.add(pnlEnablers);
            contentPane.add(scroll);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setLocation(240, 280);
            UIManager.put("List.background", Color.lightGray);
            UIManager.put("List.selectionBackground", Color.orange);
            UIManager.put("List.selectionForeground", Color.blue);
            UIManager.put("Label.disabledForeground", Color.magenta);
            SwingUtilities.updateComponentTreeUI(f);
            f.pack();
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    f.setVisible(true);
                }
            });
        }
    
        @Override
        public void itemStateChanged(ItemEvent event) {
            JCheckBox checkBox = (JCheckBox) event.getSource();
            int index = -1;
            for (int i = 0; i < ITEMS.length; i++) {
                if (ITEMS[i].equals(checkBox.getText())) {
                    index = i;
                    break;
                }
            }
            if (index != -1) {
                enabledFlags[index] = checkBox.isSelected();
                jList.repaint();
            }
        }
    
        public static void main(String args[]) {
            SwingUtilities.invokeLater(new JListDisabledItemDemo());
        }
    
        private class DisabledItemListCellRenderer extends DefaultListCellRenderer {
    
            private static final long serialVersionUID = 1L;
    
            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                Component comp = super.getListCellRendererComponent(list, value, index, false, false);
                JComponent jc = (JComponent) comp;
                if (enabledFlags[index]) {
                    if (isSelected & cellHasFocus) {
                        comp.setForeground(Color.black);
                        comp.setBackground(Color.red);
                    } else {
                        comp.setForeground(Color.blue);
                    }
                    if (!isSelected) {
                        if ((value.toString()).trim().equals("yellow")) {
                            comp.setForeground(Color.orange);
                            comp.setBackground(Color.magenta);
                        }
                    }
                    return comp;
                }
                comp.setEnabled(false);
                return comp;
            }
        }
    
        private class DisabledItemSelectionModel extends DefaultListSelectionModel {
    
            private static final long serialVersionUID = 1L;
    
            @Override
            public void setSelectionInterval(int index0, int index1) {
                if (enabledFlags[index0]) {
                    super.setSelectionInterval(index0, index0);
                } else {
                    /*
                     * The previously selected index is before this one,
                     * so walk forward to find the next selectable item.
                     */
                    if (getAnchorSelectionIndex() < index0) {
                        for (int i = index0; i < enabledFlags.length; i++) {
                            if (enabledFlags[i]) {
                                super.setSelectionInterval(i, i);
                                return;
                            }
                        }
                    } /*
                     * Otherwise, walk backward to find the next selectable item.
                     */ else {
                        for (int i = index0; i >= 0; i--) {
                            if (enabledFlags[i]) {
                                super.setSelectionInterval(i, i);
                                return;
                            }
                        }
                    }
                }
            }
        }
    }
    

    【讨论】:

    • 但我在一行中造句。例如:“好——本质上是积极的或可取的”。在 jlist 的那一行中,我希望“好”这个词有灰色,它的定义应该有蓝色。它们在同一个 jlist 中,有可能做到这两种颜色吗?
    • 是的,有三个 - 1) 按照 (@trashgod) 的建议和 (@Yasin Okumus) 的建议对任何 JComponents 使用 Html,- 2) 放在那里 JTextArea + Caret + HightLighter (little但复杂但不使用Html语法),-3)将一些Jlabels放入JPanel,这个面板作为ListItem
    • -1 用于答案中的随机代码并在评论中隐藏真正的答案 ;-)
    • @mKorbel 实际上我使用了一种方法,这就是为什么它需要时间来工作.. 但现在可以了。非常感谢..!
    猜你喜欢
    • 2011-03-06
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 2012-03-22
    • 2013-12-26
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多