4

I have a list of words in my Jlist and beside of every words are their definitions. I want that the font of the words are having a different colors than their definition. My question is that, Is it possible to have a two different colors in one Jlist?

Do I have to use ListCellRenderer?

Thanks...

papski
  • 1,241
  • 5
  • 28
  • 52
  • 1
    Yes, but `DefaultListCellRenderer` is a `JLabel`, which can use HTML. – trashgod Sep 08 '11 at 04:52
  • 1
    still not read or not understood the tutorial on renderers? The answer doesn't change, however often you ask "do I have to use a ListCellRenderer" - it is and always will be a resounding _YES_ – kleopatra Sep 08 '11 at 09:53
  • 1
    anyway, what exactly is it you didn't understand of @Thomas answer in http://stackoverflow.com/questions/7331388/how-to-set-the-color-of-a-font? He already gave you two options ... – kleopatra Sep 08 '11 at 09:58
  • @kleopatra actually I used a method thats why it takes time to work.. but now its ok. ;-) – papski Sep 08 '11 at 12:14

2 Answers2

8

I think you may use "<html>" style. It might look some odd but if you start your text (String value) by "<html>" (not capital letter HTML), you will be able to use html codes on your labels.

As an example;

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

Similar for JList.

Yasin Okumuş
  • 2,299
  • 7
  • 31
  • 62
2
Is it possible to have a two different colors in one Jlist? 

enter image description here

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;
                        }
                    }
                }
            }
        }
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • but I am making a sentence in one line. example: "good - Being positive or desirable in nature". in that line in jlist, I want the word "good" to have a color of gray and its definition should have a color of blue. They are inside in the same jlist, is it possible to do that two colors? – papski Sep 08 '11 at 08:53
  • 1
    yes there are three - 1) by using Html for any of JComponents as suggested by (@trashgod) and post by (@Yasin Okumus) , - 2) put there JTextArea + Caret + HightLighter (little but complicated but without using Html syntax) , -3 ) put a few Jlabels into JPanel, this panel as ListItem – mKorbel Sep 08 '11 at 09:48
  • 3
    -1 for random code in the answer and hiding the real answer in a comment ;-) – kleopatra Sep 08 '11 at 10:00
  • @mKorbel actually I used a method thats why it takes time to work.. but now its ok. thanks a lot..! – papski Sep 08 '11 at 12:15