JLabel:如果文本不合适,则挤压文本

时间:2018-11-23 14:18:36

标签: java html swing jlabel text-rendering

我在受限制的空间(JTable中有JLabel,并且标签内的文本太长时,它会被截断。是否可以通过仅水平挤压使文本适合分配的空间?

请参见这些示例中的上方Jlabel:

enter image description here

文本是HTML格式的,所以我不能自己在自定义的JPanel组件上拉线。没有图标。

由于我在输入问题时已经解决了该问题,因此根据meta,我将分享答案。

1 个答案:

答案 0 :(得分:1)

我将其设置为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();
        }
    }
}