Word wrapping in JList elements

I have a JList with very long element names that make the horizontal scrollbar appear in the scroll pane.

Is there anyway that I can wrap words so that the entire whole name of the element is displayed in 2 lines, but can be selected with one click? IE, it should still behave as a separate element, but display in two lines.


Here is what I did after watching the example below

I added a new class to my MyCellRenderer project, and then added the code MyList.setCellRenderer(new MyCellRenderer(80)); into the post creation code on my list. Anything else I need to do?

+8
java swing jlist jscrollpane
source share
3 answers

Yes, using Andrew code, I came up with something like this:

 import java.awt.Component; import javax.swing.*; public class JListLimitWidth { public static void main(String[] args) { String[] names = { "John Smith", "engelbert humperdinck", "john jacob jingleheimer schmidt" }; MyCellRenderer cellRenderer = new MyCellRenderer(80); JList list = new JList(names); list.setCellRenderer(cellRenderer); JScrollPane sPane = new JScrollPane(list); JPanel panel = new JPanel(); panel.add(sPane); JOptionPane.showMessageDialog(null, panel); } } class MyCellRenderer extends DefaultListCellRenderer { public static final String HTML_1 = "<html><body style='width: "; public static final String HTML_2 = "px'>"; public static final String HTML_3 = "</html>"; private int width; public MyCellRenderer(int width) { this.width = width; } @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { String text = HTML_1 + String.valueOf(width) + HTML_2 + value.toString() + HTML_3; return super.getListCellRendererComponent(list, text, index, isSelected, cellHasFocus); } } 
+19
source share

This can be made even simpler. You can create a JList using consatructor using ListModel. In CustomListModel extends AbstractListModel, the getElementAt () method can return a String with the same text in html format. Thus, this method does the same without modifying the rendering of the cells.

0
source share

You can also dynamically calculate the width (instead of a fixed value):

 String text = HTML_1 + String.valueOf(**list.getWidth()**) + HTML_2 + value.toString() + HTML_3; 

So, if the panel resizes the list, the wrapper remains true.

Update

And the result will look like this: enter image description here

-one
source share

All Articles