How to make one item in a JList bold?
Asked Answered
S

1

5

I'm making enhancements to a Swing app (never done Swing programming before), and need to be able to make a single text item in a JList bold. I've seen a few posts where they said to just put "<html><b>" and "</b></html>" around the string. Are you serious, that seems like such a hack. It's also possible in the future that we'll want to change the background color of an item in the JList - would that also be possible with HTML tags?

Another suggestion I've seen is to call the setCellRenderer() method on the JList with your own object that implements the ListCellRenderer interface. But I'm not sure that can do what we want. It seems the ListCellRenderer has a getListCellRendererComponent() method where you set how an item will be displayed depending on whether it is selected or has the focus. But we want to have one item in the JList be bold depending on what our business logic determines, and it may be an item that is neither selected nor has the focus. I haven't seen any good examples of this ListCellRenderer, so I'm not sure if it's the approach we want.

Someplace answered 3/6, 2011 at 7:2 Comment(0)
C
7

The ListCellRenderer component also gets the object to be displayed and thus you can format based on whatever logic you have to. You can find the introduction to custom rendering here and an example of a renderer here (it sets the background based on dnd location but the idea is the same for other logic as well).

The following code gives you an idea of how it may be implemented.

class MyCellRenderer extends DefaultListCellRenderer {

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

        if ("TEST".equals(value)) {// <= put your logic here
            c.setFont(c.getFont().deriveFont(Font.BOLD));
        } else {
            c.setFont(c.getFont().deriveFont(Font.PLAIN));
        }
        return c;
    }
}
Coucher answered 3/6, 2011 at 7:15 Comment(1)
OK, so right now we are calling addElement() on the DefaultListModel to add Strings (the names of our objects). After I implement the ListCellRenderer, I take it that I will call addElement() with our actual objects instead. Then I can replace your line: ` if ("TEST".equals(value)) ` with this line: ` if (value.isDefault()) ` because our objects have an isDefault() method to determine if it is the default object, and if so, then that item should have its name displayed in bold. Oh and I take it I will need to call setText() with the object's name.Someplace

© 2022 - 2024 — McMap. All rights reserved.