Highlighting JList Items

Hello
Could anybody let me how to change the color of Few Items of JList. I know how to change the foreground color of an item which is selected. But, I need to show few items of JList in different color.
Thanks in advance

please can you tell us where is/are ..., could you able to demostrate your issue, now
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JListDisabledItemDemo implements ItemListener, Runnable {
    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);
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);
JFrame f = new JFrame("JList and Colors");
Container contentPane = f.getContentPane();
contentPane.setLayout(new GridLayout(1, 2));
contentPane.add(pnlEnablers);
contentPane.add(scroll);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(240, 280);
f.setLocationRelativeTo(null);
UIManager.put("List.background", Color.red);
UIManager.put("List.selectionBackground", Color.orange);
UIManager.put("List.selectionForeground", Color.blue);
UIManager.put("Label.disabledForeground", Color.magenta);
SwingUtilities.updateComponentTreeUI(f);
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) {
if (enabledFlags[index]) {
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
Component comp = super.getListCellRendererComponent(list, value, index, false, false);
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 {
if (getAnchorSelectionIndex() < index0) {
for (int i = index0; i < enabledFlags.length; i++) {
if (enabledFlags[i]) {
super.setSelectionInterval(i, i);
return;
} else {
for (int i = index0; i >= 0; i--) {
if (enabledFlags[i]) {
super.setSelectionInterval(i, i);
return;

Similar Messages

  • Highlight a word within a JList Item

    I would like to highlight a word red within a JList item. For example, a user has a number of words to select from such as can or will. I would like them to select that word and any entries within the list I would like highlighted. I ONLY want the word within a JList item though and not the whole JList item. I know how to do this with a TextField but am having trouble doing this within a JList. Any help would be greatly appreciated.

    Use html syntax to set color/size of a list item. Try this simple example:
    import java.awt.*;
    import javax.swing.*;
    class Testing extends JFrame {
      public Testing() {
        String [] list = {
           "<html><body>Black <font size=15>Black</font> Black",
           "<html><body>Red <font color=red size=10>Red</font> Red ",
           "<html><body>Blue <font color=blue size=5>Blue</font> Blue"
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new BorderLayout());
        JList jlist = new JList(list);
        JScrollPane spane = new JScrollPane(jlist);
        panel.add(spane);
        getContentPane().add(panel);
        setSize(200,200);
      public static void main(String[] args){
        new Testing().setVisible(true);
    }

  • Double click for JList items selection

    I would like to select JList items only by double clicking on them. I can write a mouse listener for detecting double clicks by my own (and handle it afterwards), by please tell me how to turn the default behavior off (selecting items by clicking one time).
    Thanks in advance
    Marek

    I would like to select JList items only by double clicking on them. Well the standard is to select or highlight on a mouseClick or by using the arrow keys on the keyboard.
    Then once you have a selected item you can perform and Action on the item by double clicking or by using the enter key. Remember you should always be able to use either the keyboard or the mouse to perform any given function.
    This posting shows my solution for the above scenario:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=626866

  • How to center JList  items

    Hi,
    I want to center my Jlist item instead of leave them in the left like usual. My List contains pictures and for the beauty of the design it's better to have the image in the center of each cells. How to do it?
    thanks.

    Do you know how to make a JLabel which contains a centred icon? Now make a ListCellRenderer that uses one of those to render your images in the JList.

  • How to save JList items!

    hello,
    i m creating a class that has three JList components.
    My problem is how to save the each JList items into a seperate logfile(ie. text file).

    More info required:
    What are in the JList? Strings? Custom objects?
    Do you know basic file IO?
    http://java.sun.com/docs/books/tutorial/essential/io/index.html
    What you will need to do is get the model, ilterate over each element, then write that element out. If the element is a string, then that is easy, just create a FileWriter, and write the string, followed by a new line.
    If it is a custom object, then the task is harder, and you need to decide how that object should be represented.
    If you are after a computer readable view of the model, rather than a human readable, which can easily be read by Java back into a ListModel, then you want to look at XMLEncoder and XMLDecode, or the Serializing Objects tutorial.
    http://java.sun.com/docs/books/tutorial/uiswing/components/list.html

  • Dynamically changing size of JList items?

    Hello!
    I'm working on an application which kind of revolves around a JList with a custom ListCellRenderer. Now, it all works rather good as it is, but I want the selected JList item to show more detailed information about the selected value, and thus I need it to be bigger then the not selected items. The thing is that no matter what I do I can't seem to make the JList adopt to the new size of the selected item, which results in only half of the stuff in the selected item being shown.
    Is there any way to do this it would be great! (I bet there is some really simple way which I have simply overlooked.)
    And, fyi: The component returned by getListCellRendererComponent is a JPanel which consists of three JLabels using a GridLayout. The selected component is generally the same, but with an extra row in the GridLayout.
    Any help/suggestions will be greatly appreceated!
    Yours, Jiddo.

    I have tried with a couple of different layout managers, and none of them (except for this one) seems to offer me the layout I need. Also, I have tried making it return different instances depending on if it is selected or not. The non-selected one has only one row in the layout while the selected has two. Here is a screenshot of how it looks:
    http://img211.imageshack.us/img211/2779/jlistes1.jpg
    Yours, Jiddo.

  • How to highlight tree item ?

    Hello everybody !
    I have a question : how to highlight a tree item on a condition ? (please see the attached vi and the pictures for a clearer explanation of the problem)
    I am using LabView 2014.
    Thank you very much !
    Solved!
    Go to Solution.
    Attachments:
    Highlight_tree_item.vi ‏13 KB

    Have patience.  You only aske the question about 40 minutes earlier.
    You highlight rows like you want by writing values to the tree control.  Don't mess with cell background color.
    Are you trying to highlight multiple items?  If so, then right click on the control and allow it to select 0 or more items.  As soon as you select a mode with the possibility of more than one item, the tree values become an array of strings rather than just a string.  You will need to build an array of strings that you will write to the control's local variable to highlight the multiple items.

  • Illustrator CS2 doesn't highlight selected items any more

    hello, i use illustrator cs2, and since a few days - without having changed any options - the program doesn't highlight selected items any more. neither does it highlight selected text... so editing items becomes a guessing game which is extremeley annoying... i can't find anything on this in the help file... i hope anybody here can help me!
    thx!

    thanks! that was one quick reply!

  • Highlighting an item in a scene

    I am trying to "highlight" certain items in a scene in my movie.
    The topic is on welding, and I start by saying "gather your supplies...you will need...a welding mask, protective gloves, a torch, etc..." and as I say each item, I want it to "light up."
    I have a scene playing as I say "you will need..." and then I inserted a freeze frame & turned the color down on it (so it is nearly black & white). Then I laid that same freeze frame above it on a different track, and used the crop feature to highlight the items as they are listed. It just doesn't look very clean though...since you can only do a perfect square, and everything I want to highlight is not square.
    I tried the vignetting effect, but that just vignettes the whole scene, you can't specify where you want it to highlight.
    Please let me know some suggestions for how to acheive the look I am going for. Let me know if you need more details.
    Thanks,
    Lauren

    There are many possibilities for doing what you want.
    Steve G. has provided two.
    This article covers some more, plus Track Matte Keying, that really has unlimited possibilities: http://forums.adobe.com/message/4575874#4575874
    One variation on Track Matte Keying would be to perhaps make your video at that point B/W, and then with Track Matte Keying, change the desired object to full color.
    One can also "call out" objects/subjects with the techniques in this article: http://forums.adobe.com/message/3702803#3702803
    Another technique, which is a variation on above, would be to create a Shape that is only Stroked (not Filled), that surrounds the object, with a bright Stroke and perhaps a Glow.
    Lots of possibilities.
    Good luck,
    Hunt

  • Highlight an item in a SQL-report

    Hello,
    I have a table in which items are stored with a column "name" and a column "correct".
    I need to highlight an item (put backgroundcolor in red) in a SQL-report based on the fact if the value of the column "correct" of the item is False. I don't know how I can do this? Can anyone help?
    Thanks in advance,
    Bram.

    Hello Bram,
    Something like:
    select "DEMO_PRODUCT_INFO"."PRODUCT_ID" as "PRODUCT_ID",
          CASE WHEN PRODUCT_AVAIL='N'
             THEN '<span style="background:red">'||product_name||'</span>'
             ELSE product_name
             END  "PRODUCT_NAME",
          "DEMO_PRODUCT_INFO"."PRODUCT_AVAIL" as "PRODUCT_AVAIL"
    from "DEMO_PRODUCT_INFO" "DEMO_PRODUCT_INFO"Greetings,
    Roel
    http://roelhartman.blogspot.com/
    You can reward this reply by marking it as either Helpful or Correct ;-)

  • I used to be able to use the tools, edit image and highlight certain items in the pdf photos. why can I not now?

    I used to be able to use the tools, edit image and highlight certain items in the pdf photos. why can I not now?

    Usually Acrobat has linked to PhotoShop to do the photo editing. You might check the updates for Acrobat and PhotoShop.

  • Delete Selected JList Item on Pressing Delete Key

    Hi,
    I have to delete selected JList item ((in JFrame using java Swing) after pressing Delete key. Please provide me code for this.
    Thanks
    Nitin

    Again read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/list.html]How to Use Lists and [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings.
    Are you sensing a common theme here? Do some reading on your own. The tutorial has most of the information you need.

  • Editing Jlist Item Contents....

    hi,
    i want to edit the contents of a Jlist Item.
    any help???
    Manikandan

    in your ListSelectionListener you must check if the event is one of multiple change events. In your case you get one event when the mouse first selects an item and possible more when you move the cursor over the other entries. If you are only interested in the final selection check if e.getValueIsAdjusting() is false.
    // not interested in events if they are not final
    if (e.getValueIsAdjusting())
        return;
    // do what ever you want
    System.out.println(colorList.getSelectedValue());
    ...Hope this helps!

  • Rendering JList items instantly

    hi friends
    I wanna know how to rendering JList items instantly without selecting any item,so the rendering of the item has to be automatically.
    thank you very much

    Well how does the icon change? Normally changes to the data are done by updating the model, in which case the list will get painted automatically.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • Selection of JList item

    hi friends
    i am using JList component.i have added many item in Jlist.by keyboard up and down arrow key i can make them highlighted and then select. but i want few item of JList never highlighted and select when i press up and down arrow key . For example, If i do not want to select 2nd item in the list then by pressing down arrow key selection should be jumped from first to third item skipping second item.
    How to do that?

    I might be wrong but I think you need to code for it.
    I have created a code using key binding. To use if you need to skip an item you need to hold down the control key and use the up and down arrow to navigate and once you have selected an item release control key and press enter, vice-versa.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ListFocusDemo extends JFrame {
        public void createAndShowUI() {
            final JList myList = new JList(new String[] {"My data 1","My data 2",
            "My data 3","My data 4"});
            JScrollPane scrollPane = new JScrollPane(myList);
            InputMap map = myList.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "myAction");
            myList.getActionMap().put("myAction", new AbstractAction() {
                public void actionPerformed(ActionEvent evt) {
                    int lead = myList.getLeadSelectionIndex();
                    if(lead > -1 && !myList.isSelectedIndex(lead)) {
                        myList.getSelectionModel().addSelectionInterval(lead, lead);
                    } else if(lead > -1 && myList.isSelectedIndex(lead)) {
                        myList.getSelectionModel().removeSelectionInterval(lead, lead);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            pack();
            setLocationRelativeTo(null);
            setVisible(true);
        public static void main(String[] args) {
            Runnable run = new Runnable() {
                public void run() {
                    new ListFocusDemo().createAndShowUI();
            SwingUtilities.invokeLater(run);
    }

Maybe you are looking for

  • After reinstalling 10.2.3 and updating to 10.2.8, I get dead blue screen

    Due to recent "overlapped extent..." problem on my hard-drive (which created startup problems) a separate posting on this forum advised that I reinstall OS X, which I did. I followed the "Archive & Install (Preserving Settings)..." method. First, 10.

  • TS1567 Iphone is recognized in windows but not itunes 11

    Iphone is recognized in windows but not itunes 11

  • Poll:  Oracle 9i (backward "CLIENT" compatibility)

    I am just curious how many people upgraded their Oracle DB to 9i and upgraded their client box also? If yes, please state your experience 1. Good (explain) 2. Bad (explain) 3. Ugly (explain) We have 100s of server running various version of clients (

  • Duplicate in numbers

    I have several sheets containing charts and diagram. I want to duplicate a sheet and modify data but duplicate cannot work! By Duplicate, Copy/Paste, Option key + slip.  Any method runs OK!

  • How to play through to tv monitor?

    Tom Wolsky (FCE 2, editing workshop) advises to do color correction on tv monitor, not computer monitor. How do I play through my sony vx 1000 from computer to monitor? Thanks, David