Problem displaying components of JList

霸气de小男生 提交于 2019-12-11 02:39:31

问题


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?


回答1:


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




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/5631048/problem-displaying-components-of-jlist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!