我正在尝试创建一些用于特定目的的特殊组件,在该组件上我需要绘制HTML字符串,这是示例代码:
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格式,它愚蠢地按原样绘制字符串。
有什么办法可以使这项工作吗?
我找到了一种简洁的模拟方法paintHtmlString; 这是代码:
paintHtmlString
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); } }