绘画JLabel切断了HTML文本

时间:2013-07-09 19:40:04

标签: java html spring jlabel bufferedimage

我正在尝试使用html作为文本将JLabel绘制到BufferedImage,但它总是在中间(垂直)打印文本,并切断右侧的文本。

这是我的代码:

public static void test() throws IOException
{
    int width = 100;

    JLabel label = new JLabel();
    label.setText("<html><body><p>asdf asdfasdf asdfsdf asdfasdf asdfasdf asdfasdfasdfasdf asdfasdfasdfa sdfasd fasdf asdfasdf asdfasdf asdfasdfasdfa sdfasdf</p></body></html>");
    Dimension size = getPreferredSize(label.getText(), true, width);

    label.setSize(size);

    BufferedImage image =
            new BufferedImage(
                    label.getWidth(),
                    label.getHeight(),
                    BufferedImage.TYPE_INT_RGB);

    Graphics g = image.getGraphics();
    g.setColor(Color.LIGHT_GRAY);
    g.fillRect(0, 0, 500, 900);
    label.paint(g);

    ImageIO.write(image, "png", new File("testImage.png"));
}

private static final JLabel resizer = new JLabel();

public static java.awt.Dimension getPreferredSize(
        String html,
        boolean width,
        int prefSize)
{

    resizer.setText(html);

    View view =
            (View) resizer
                    .getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey);

    view.setSize(width ? prefSize : 0, width ? 0 : prefSize);

    float w = view.getPreferredSpan(View.X_AXIS);
    float h = view.getPreferredSpan(View.Y_AXIS);

    return new java.awt.Dimension((int) Math.ceil(w), (int) Math.ceil(h));
}

这是结果图像:

enter image description here

1 个答案:

答案 0 :(得分:-1)

我认为html自动换行是由swing线程循环中的某些东西处理的,如果你正在做这个循环作为actionlistener的表单,那么它就不能重新计算html