如何让 JTextPane 显示省略号以表示文本溢出?
我使用 JTextPane 作为表格单元格渲染器来显示富文本。当文本太长而无法放入单元格时,它会被截断。我想模仿 JLabel 行为,即显示省略号 (...) 来提醒用户部分文本不可见。以前有人这样做过吗?
在斯坦尼斯拉夫的帮助下,我最终采用了解决方案。该算法的工作原理是每次从 StyledDocument
末尾切掉一个字符,附加“...”并将生成的首选宽度与表格单元格宽度进行比较。这是低效的,特别是在字符串很长的情况下,但对我来说不是问题。可以优化。以下内容进入渲染器的 getTableCellRendererComponent
m_dummyTextPane.setDocument(doc);
m_dummyTextPane.setSize(Short.MAX_VALUE, table.getRowHeight());
int width = m_dummyTextPane.getPreferredSize().width;
int start = doc.getLength() - 1;
while(width >= table.getColumnModel().getColumn(col).getWidth() && start>0) {
try {
doc.remove(Math.min(start, doc.getLength()),
doc.getLength() - Math.min(start, doc.getLength()));
doc.insertString(start, "...", null);
} catch (BadLocationException e) {
e.printStackTrace();
break;
}
start--;
width = m_dummyTextPane.getPreferredSize().width;
}
I am using JTextPane as a table cell renderer to display rich text. When the text is too long to fit inside a cell, it is truncated. I would like to mimic the JLabel behavior, i.e. show ellipsis (...) to alert the user that part of the text is not visible. Has anyone done this before?
Solution I ended up adopting, with help from StanislavL. The algorithm works by chopping off one character at a time off the end of StyledDocument
, appending "..." and comparing resulting preferred width to table cell width. This is inefficient, especially in case of very long strings, but not a problem in my case. Can be optimized. The following goes into your renderer's getTableCellRendererComponent
m_dummyTextPane.setDocument(doc);
m_dummyTextPane.setSize(Short.MAX_VALUE, table.getRowHeight());
int width = m_dummyTextPane.getPreferredSize().width;
int start = doc.getLength() - 1;
while(width >= table.getColumnModel().getColumn(col).getWidth() && start>0) {
try {
doc.remove(Math.min(start, doc.getLength()),
doc.getLength() - Math.min(start, doc.getLength()));
doc.insertString(start, "...", null);
} catch (BadLocationException e) {
e.printStackTrace();
break;
}
start--;
width = m_dummyTextPane.getPreferredSize().width;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用此 http://java-sl.com/tip_text_height_measuring.html 来测量以下内容:固定宽度。如果需要的空间多于可用空间,只需在 JTextPane 上绘制一些内容即可。
我也喜欢垃圾神的滚动想法。 (+1)
You can use this http://java-sl.com/tip_text_height_measuring.html to measure content for the fixed width. If it requires more space than available just paint something over the JTextPane.
I like the trashgod's idea with scroll too. (+1)
如果滚动条是可接受的替代方案,但空间非常宝贵,则您可以指定
JComponent.sizeVariant
,如 调整组件大小 和 使用客户端属性。If a scroll bar is an acceptable alternative, but space is at a premium, you may be able to specify a
JComponent.sizeVariant
, as discussed in Resizing a Component and Using Client Properties.我通过覆盖
paint()
和getToolTipText()
方法来完成此操作,如果它太长,则将其放入工具提示中:I did it by just overriding the
paint()
andgetToolTipText()
methods, to put it in the tooltip if it's too long: