Hunsu
Hunsu

Reputation: 3381

How to print a part of an item in bold with JList

I use a DefaultListCellRenderer to render an array of Strings (its not really an array of Strings, its just to explain my question). The getListCellRendererComponent function take an Array and must print an element of that array in bold. My current idea is to use Html tags (like <b>theElement</b>) but I have read that this is not good practice. The code below is my current idea.

if (value instanceof ArrayList) {
     ArrayList<String> al = (ArrayList<String>) value   
     String s = "<html><b>" + al.get(0) + "</b></html>\n";
     al.remove(0);
     for(String c : al)
         s += c + "\n";
     setText(s);

Upvotes: 0

Views: 246

Answers (1)

David Koelle
David Koelle

Reputation: 20824

You can use HTML in a JList, and I'm not aware of why that would be a bad practice - unless when the user selects a row, you are now checking whether the selected item is <b>thing</b> rather than just thing. But if you're doing something better than string comparisons on the selected list items, this shouldn't be a problem.

If you're using DefaultListCellRenderer, this is the only way I know that you can make some part of an item bold.

See also Can Items in a JList be formatted as HTML

Upvotes: 1

Related Questions