Vamsi Emani
Vamsi Emani

Reputation: 10302

Problem displaying components of JList

I am trying to dsiplay the twitter timeline in a Jlist component. I have already fixed the size of my frame and the cell height and cell width of the JList too with the following code.

jlist.setFixedCellHeight(50);
jlist.setFixedCellWidth(70);

I find that the height and width of each cell are fine but if the content of the tweet inside the cell exceeds the width it is not displaying the further part of the tweet.

For example: Assume that 70 width exactly fits the tweet "I am good"

Suppose if the tweet is "I am good and great" The tweet is getting displayed as "I am good....." The exceeded part of the tweet is not getting displayed.

What I want to do here is, I want the rest out part of the tweet to be displayed below the line as I do have sufficient height to display the tweet in a second line. In the same example, within the cell, I want the content to be displayed as

"I am good

and great"

How can I achieve this?

Upvotes: 2

Views: 1286

Answers (3)

Vamsi Emani
Vamsi Emani

Reputation: 10302

As kleopatra said,

We need a custom ListCellRenderer which returns a component that supports multiple lines of text. The default renderer returns a JLabel with is single-line only. We need to create such a renderer which returns a JTextArea that can wrap multiple lines within it. The following is the simple code for this.

public class CustomListRenderer implements ListCellRenderer {

   @Override
   public Component getListCellRendererComponent(JList list, Object value, int index,
        boolean isSelected, boolean cellHasFocus) {

        JTextArea renderer = new JTextArea(3,10);
        renderer.setText(value.toString());
        renderer.setLineWrap(true);
        return renderer;
   }
}

We need to add the following line to set the cell renderer to the jlist.

jlist.setCellRenderer(new CustomListRenderer());

Upvotes: 2

kleopatra
kleopatra

Reputation: 51525

you need a custom ListCellRenderer which returns a component that supports multiple lines of text. The default renderer returns a JLabel with is single-line only. You can implement f.i a renderer which returns a JTextArea

Upvotes: 1

qwerty
qwerty

Reputation: 3869

quoting from the JList java doc

JList doesn't implement scrolling directly. To create a list that scrolls, make it the viewport view of a JScrollPane. For example:

JScrollPane scrollPane = new JScrollPane(myList);

// Or in two steps: JScrollPane scrollPane = new JScrollPane(); scrollPane.getViewport().setView(myList);

Upvotes: 0

Related Questions