java - JLabel: Squish text if it doesn't fit
问题描述
I have JLabels in a constrained space (JTable
) and when the text inside the label is too long, it's truncated. Is there a way to make the text fit in the allotted space by only horizontal squishing?
See the upper Jlabel in these examples:
The text is HTML formatted so I can't just drawstring on a custom JPanel component myself. There's no icon.
Since I've solved this question while typing it, in accordance with meta I'll share the answer.
解决方案
我将其设置为 JLabel 的 UI:
它将文本呈现为屏幕外图像,然后将该图像调整为 JLabel 的比例。
[编辑] 这不适用于透明标签或带有空 HTML 文本的标签。
// Copied and modified from BasicLabelUI
private static class SquishLabelUI extends BasicLabelUI {
private final Rectangle paintIconR = new Rectangle();
private final Rectangle paintTextR = new Rectangle();
private String layout(JLabel label, FontMetrics fm, int width, int height) {
Insets insets = label.getInsets(null);
String text = label.getText();
Rectangle paintViewR = new Rectangle(insets.left,
insets.top,
width - (insets.left + insets.right),
height - (insets.top + insets.bottom));
paintIconR.setBounds(0, 0, 0, 0);
paintTextR.setBounds(0, 0, 0, 0);
return layoutCL(label, fm, text, null, paintViewR, paintIconR, paintTextR);
}
@Override
public void paint(Graphics g, JComponent c) {
JLabel label = (JLabel)c;
layout(label, SwingUtilities2.getFontMetrics(label, g), c.getWidth(), c.getHeight());
View v = (View)c.getClientProperty(BasicHTML.propertyKey);
Dimension size = getPreferredSize(label);
BufferedImage img = label.getGraphicsConfiguration()
.createCompatibleImage(size.width, size.height, TRANSLUCENT);
Graphics2D g2 = img.createGraphics();
try {
g2.setColor(label.getBackground());
g2.setClip(0, 0, size.width, size.height);
g2.fillRect(0, 0, size.width, size.height);
v.paint(g2, new Rectangle(0, 0, size.width, size.height));
int renderWidth = Math.min(size.width, paintTextR.width);
Image img2 = img.getScaledInstance(renderWidth, paintTextR.height, Image.SCALE_SMOOTH);
g.drawImage(img2, paintTextR.x, paintTextR.y, null);
} finally {
g2.dispose();
}
}
}
推荐阅读
- linux - 角色更改后 rsyslog 客户端无法用作 rsyslog 服务器
- r - 有没有办法为空值执行 if 语句
- android - 首次启动应用程序时不会调用 onReceive 方法
- php - Laravel - 将复选框数组存储为数据透视表中的布尔值
- node.js - Node Js Debugger 地址已经在使用中
- caching - rust-diesel 上没有缓存
- azure - 将 localhost 添加到 Azure AD/应用注册重定向 URL 是否存在安全风险?
- angular - 在github页面上部署我的角度网站没有错误但无法正常工作
- sql - SQL 查询。获取按 desc 排序的相似行
- excel - 多个空 Excel VBA 项目