How to make one element in JList in bold?

I am making improvements for a Swing application (I have never done Swing programming before) and should be able to make a separate text element in JList in bold. I saw several posts where they said to just put "<html><b>" and "</b></html>" around the line. Seriously, this looks like such a hack. It is also possible that in the future we will want to change the background color of the element in the JList - is this also possible with HTML tags?

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

+4
source share
1 answer

The ListCellRenderer component also gets the object to display, and so you can format based on any logic. You can find an introduction to custom rendering here and an example of a renderer here (it sets the background based on the dnd location, but the idea is the same for different logic).

The following code gives you an idea of ​​how it can 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; } } 
+6
source

All Articles