根据内容扩展 JList 行高
我有一个简单的问题,这完全让我发疯。
我有一个 JList,并希望其单元格根据其内容(即可变长度的文本)进行扩展。
所以我创建了一个 CustomCellRenderer,如下所示:
@Override
public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean hasFocus)
{
final String text = (String) value;
final JTextArea ta = new JTextArea();
ta.setText(text);
ta.setFont(new Font("Dialog", Font.PLAIN, (int) Theme.FONTSIZE_TEXT));
ta.setForeground(Theme.FONTCOLOR_CONTENT);
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setColumns(0);
ta.setBorder(BorderFactory.createEmptyBorder(10, Theme.PADDING, 0, 0));
return ta;
}
但单元格只有一个文本行高,而 JTextArea 的其余部分被切断。如果我添加,
ta.setPreferredSize(new Dimension(0, 70));
行高将为 70,并且我可以看到 JTextArea 的更多文本,但仍然不是全部。
有没有办法让 JList 展开其单元格,以便显示 JTextArea 的全部内容?
I have a simple problem which totally drives me crazy.
I have a JList, and would like its cells to expand depending on their content, which is text of variable length.
So I created a CustomCellRenderer like so:
@Override
public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean hasFocus)
{
final String text = (String) value;
final JTextArea ta = new JTextArea();
ta.setText(text);
ta.setFont(new Font("Dialog", Font.PLAIN, (int) Theme.FONTSIZE_TEXT));
ta.setForeground(Theme.FONTCOLOR_CONTENT);
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setColumns(0);
ta.setBorder(BorderFactory.createEmptyBorder(10, Theme.PADDING, 0, 0));
return ta;
}
but the cells are only one text line high and the rest of the JTextArea is cut off. If I add
ta.setPreferredSize(new Dimension(0, 70));
I get a row height of 70 and I can see more of the JTextArea's text, but still not everything.
Is there any way to make JList expand its cells so that the whole content of the JTextArea is displayed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许有最简单和最好的方法,我认为 JTable在所有情况下使用一个 TableColumn (并且没有 TableHeader)都更好 JList,这是您的渲染 MacOX 版本,
然后输出应该为
there are maybe easiest and nicest way, I think that JTable with one TableColumn (and without TableHeader)in all cases better as JList, here is your Render MacOX version
then output should be
尝试使用 JList 的 setFixedCellHeight() 方法。
Try using JList's setFixedCellHeight() method.
不确定是否有优雅的方式。
我知道有效的一种方法如下:
在
getListCellRendererComponent()
中使用一些逻辑将
插入到需要的文本中。Not sure if there is an elegant way.
One way that I know works is as follows :
In
getListCellRendererComponent()
use some logic to insert
<br>
in to the text where desired.