具有多行文本和动态高度的摆动 JList
2022-09-03 10:10:59
我已经阅读/尝试过这些帖子,但这无济于事:
我需要的是一个返回一个面板,左侧有一个图标,右侧有一个动态长度的文本(就像在任何论坛中一样:左边是用户头像,右边是帖子文本)。我不知道这些文本,所以我无法设置固定的单元格高度。此外,文本长度因列表单元格而异。因此,每个列表单元格都需要自己的高度,具体取决于文本的长度。实际上是一个非常常见的布局...但不是为了秋千。单元格高度只是不会根据文本长度扩展。ListCellRenderer
我已经阅读了几乎所有关于动态单元格高度和多行文本的帖子,但找不到解决方案。所以我决定给一个小的SSCCE。请给我一个关于如何实现我所描述的内容的提示,或者如果您认为这很容易,请修复我的代码。JList
谢谢
以下是SSCCE:
public class MultiLineList extends JFrame
{
private static final long serialVersionUID = 1L;
public static void main(final String[] args)
{
new MultiLineList();
}
private MultiLineList()
{
setTitle("MultiLineList");
setSize(800, 450);
setResizable(true);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.getContentPane().setLayout(new BorderLayout());
final DefaultListModel model = new DefaultListModel();
model.addElement("This is a short text");
model.addElement("This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. ");
model.addElement("This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. This is an even longer text. ");
final JList list = new JList(model);
list.setCellRenderer(new MyCellRenderer());
this.add(list);
this.getContentPane().invalidate();
this.getContentPane().validate();
}
public class MyCellRenderer extends DefaultListCellRenderer
{
@Override
public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean hasFocus)
{
final String text = (String) value;
//create panel
final JPanel p = new JPanel();
p.setLayout(new BorderLayout());
//icon
final JPanel IconPanel = new JPanel(new BorderLayout());
final JLabel l = new JLabel("icon"); //<-- this will be an icon instead of a text
IconPanel.add(l, BorderLayout.NORTH);
p.add(IconPanel, BorderLayout.WEST);
//text
final JTextArea ta = new JTextArea();
ta.setText(text);
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
p.add(ta, BorderLayout.CENTER);
return p;
}
}
}