如何将文本渲染到框中并用三个点替换多余的文本
我使用自定义表格单元格渲染器渲染文本,并且如果绘制的文本超出当前单元格宽度,我想修剪它,切换到“此文本太长...”类型的表示形式,其中末尾的三个点永远不会离开边界框。 我当前的算法如下:
FontMetrics fm0 = g2.getFontMetrics();
int h = fm0.getHeight();
int ellw = fm0.stringWidth("\u2026");
int titleWidth = fm0.stringWidth(se.title);
if (titleWidth > getWidth()) {
for (int i = se.title.length() - 1; i > 0; i--) {
String tstr = se.title.substring(0, i);
int tstrw = fm0.stringWidth(tstr);
if (tstrw + ellw < getWidth()) {
g2.drawString(tstr, 2, h);
g2.drawString("\u2026", 2 + tstrw, h);
break;
}
}
} else {
g2.drawString(se.title, 2, h);
}
是否有更好的方法来确定在切换到 ... (u2026) 字符之前我应该 drawString()
有多少个字符?
I render text with a custom table cell renderer and I want to trim the text drawn if it would exceed the current cell width, switching to a "This text is to long..." kind of representation, where the three dots at the end never leaves the bounding box. My current algorithm is the following:
FontMetrics fm0 = g2.getFontMetrics();
int h = fm0.getHeight();
int ellw = fm0.stringWidth("\u2026");
int titleWidth = fm0.stringWidth(se.title);
if (titleWidth > getWidth()) {
for (int i = se.title.length() - 1; i > 0; i--) {
String tstr = se.title.substring(0, i);
int tstrw = fm0.stringWidth(tstr);
if (tstrw + ellw < getWidth()) {
g2.drawString(tstr, 2, h);
g2.drawString("\u2026", 2 + tstrw, h);
break;
}
}
} else {
g2.drawString(se.title, 2, h);
}
Is there a better way of determining how many characters should I drawString()
before switching to the ... (u2026) character?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是表的默认渲染器的默认行为,因此我不确定我是否理解这样做的原因。
但是我已经为左侧的点创建了一个渲染器(“...文本太长”),它显示了一种更完整的方法来执行您想要的操作,因为它考虑了渲染器上可能的边框和单元格间距渲染器。 查看 LeftDotRenderer。
This is the default behaviour of the default renderer for a table so I'm not sure I understand the reason for doing this.
But I've created a renderer for dots on the left ("... text is too long") which shows a more complete way to do what you want since it takes into account a possible Border on the renderer and the intercell spacing of the renderer. Check out the LeftDotRenderer.
我想不出另一种方法来达到所需的效果,但您应该能够用一个替换 2 个drawString() 调用。 自从我写 Java 以来已经有一段时间了,但我认为以下内容应该可行。
顺便说一句,我更改了变量名称,以便可以阅读代码。 :p
I can't think of another way to achieve the desired effect, but you should be able to replace the 2 drawString() calls with one. It's been a while since I've written Java but I think the following should work.
BTW, I changed the variable names so I can read the code. :p