koool
koool

Reputation: 15517

Word wrap in JList items

I have a JList with very long item names that cause the horizontal scroll-bar to appear in scroll-pane.

Is there anyway that I can word wrap so that the whole whole item name appears in 2 rows yet can be selected in one click? I.E it should still behave as a single item but be displayed in two rows.


Here is what I did after seeing the example below

I added a new class to my project MyCellRenderer and then I went added MyList.setCellRenderer(new MyCellRenderer(80)); in the post creation code of my List. Is there anything else I need to do?

Upvotes: 9

Views: 6463

Answers (3)

Dmitry V
Dmitry V

Reputation: 1

It can be done even easier. You can create JList by consatructor with ListModel. In CustomListModel extends AbstractListModel, getElementAt() method can returns String with same html-formatted text. So this way do the same without cell renderer modification.

Upvotes: -1

steph
steph

Reputation: 1

You can also compute dynamically 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, wrapping remains correct.

Update

And the result looks like this: enter image description here

Upvotes: -1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Yep, using Andrew's 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);
   }

}

Upvotes: 19

Related Questions