Rafael Carvalhido
Rafael Carvalhido

Reputation: 11

jlist won´t show whole line or way too much

newbie here.

So, I´m trying to list a few items with the Jlist, but I can´t wrap these to the next line like I do it with a jTextArea. When I put a long string for a list item, the window width enlarges with it. That is not desirable.

I, then, restricted the width of the list. It worked, but then you can´t read the text.

jList1.setModel(new javax.swing.AbstractListModel() {
    String[] strings = { "Item 1", "Item 2 is a big old thing and it won´t wrap", "Item 3" };
    public int getSize() { return strings.length; }
    public Object getElementAt(int i) { return strings[i]; }
});

The above code returns:

+---------------+
|Item 1         |
|Item 2 is a b..|
|Item 3         |
+---------------+

But I wanted:

+---------------+
|Item 1         |
|Item 2 is a big|
|old thing and i|
|t won´t wrap   |
|Item 3         |
+---------------+

The reason I want it is to be able to select a line individually even if I don´t know where each item starts.

Someone told me of putting a horizontal scroll bar and that seems nice. I just don´t know how to go about it.

Thanks for the input!

Upvotes: 1

Views: 635

Answers (1)

XWaveX
XWaveX

Reputation: 268

I assume this solves your problem. All credits go to Hovercraft Full Of Eels. I only reformatted his code and added some explanations, which seemed more helpful to me.

All you have to do is to use a custom CellRenderer for your jList, like the one below:

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);
   }

}

Here is a little example how to use it (with further explanations)

First set up your jList, like you would normally do. Then create an instance of the custom CellRenderer - in this case MyCellRenderer - with the specific line width. Finally you only have to add your renderer to your jList.

MyCellRenderer cellRenderer = new MyCellRenderer(80);
list.setCellRenderer(cellRenderer);

If you want you can also wrap your jList into a jScrollPane, which you then have to add to your underlying container instead of the list itself.

JScrollPane sPane = new JScrollPane(list);
JPanel panel = new JPanel();
panel.add(sPane);

see https://stackoverflow.com/a/8197454/3178834

Upvotes: 1

Related Questions