Swing HTML drawString [英] Swing HTML drawString

查看:25
本文介绍了Swing HTML drawString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为特定目的创建一些特殊组件,在该组件上我需要绘制一个 HTML 字符串,这是一个示例代码:

I'm trying to create some special component for a specific purpose, on that component I need to draw a HTML string, here's a sample code:

 public class MyComponent extends JComponent{
     public MyComponent(){
        super();
     }

     protected void paintComponent(Graphics g){
        //some drawing operations...
        g.drawString("<html><u>text to render</u></html>",10,10);
     }
 }

不幸的是,drawString 方法似乎无法识别 HTML 格式,它愚蠢地按原样绘制字符串.

Unfortunately the drawString method seems to be not recognizing the HTML format, it foolishly draws the string just as it is.

有什么办法可以做到吗?

Is there any way to make that work?

推荐答案

我找到了一种简短而干净的方法来模拟 paintHtmlString;这是代码:

I've found a short and a clean way to simulate the paintHtmlString; here's the code:

public class MyComponent extends JComponent {

    private JLabel label = null;

    public MyComponent() {
        super();
    }

    private JLabel getLabel() {
        if (label == null) {
            label = new JLabel();
        }
        return label;
    }

    /**
     * x and y stand for the upper left corner of the label
     * and not for the baseline coordinates ...
     */
    private void paintHtmlString(Graphics g, String html, int x, int y) {
        g.translate(x, y);
        getLabel().setText(html);
        //the fontMetrics stringWidth and height can be replaced by
        //getLabel().getPreferredSize() if needed
        getLabel().paint(g);
        g.translate(-x, -y);
    }

    protected void paintComponent(Graphics g) {
        //some drawing operations...
        paintHtmlString(g, "<html><u>some text</u></html>", 10, 10);
    }
}

感谢每一个人的帮助,我非常感谢.

Thanks to every one for the help, I do appreciate that very much.

这篇关于Swing HTML drawString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆