我正在尝试为特定的目的创建一些特殊的组件,在该组件上我需要绘制一个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格式,它愚蠢地按原样绘制字符串。
有没有办法做到这一点呢?
发布于 2011-10-15 22:19:03
我已经找到了一种简单明了的方法来模拟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);
}
}感谢每个人的帮助,我真的很感激。
发布于 2011-10-15 14:24:19
如果你是Java2D的粉丝,但为了在Swing组件和布局中最大限度地利用超文本标记语言,我建议你使用@camickr建议的组件方法。如果需要,您可以使用JTable等人中看到的flyweight renderer approach,其中单个组件重复用于绘图。下面的示例是该技术的一个非常简化的概要,仅更改颜色和位置。
附录:更新的示例;另请参阅CellRendererPane和。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.CellRendererPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/** @see http://stackoverflow.com/questions/7774960 */
public class PaintComponentTest extends JPanel {
private static final int N = 8;
private static final String s = "<html><big><u>Hello</u></html>";
private JLabel renderer = new JLabel(s);
private CellRendererPane crp = new CellRendererPane();
private Dimension dim;
public PaintComponentTest() {
this.setBackground(Color.black);
dim = renderer.getPreferredSize();
this.add(crp);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < N; i++) {
renderer.setForeground(Color.getHSBColor((float) i / N, 1, 1));
crp.paintComponent(g, renderer, this,
i * dim.width, i * dim.height, dim.width, dim.height);
}
}
private void display() {
JFrame f = new JFrame("PaintComponentTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setSize(dim.width * N, dim.height * (N + 1));
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new PaintComponentTest().display();
}
});
}
}发布于 2011-10-15 12:19:52
正如其他人评论的那样,Swing组件支持HTML3.2和基本样式。
有关如何在paintComponent(Graphics)方法中利用该功能的详细信息,请参阅this thread上的LabelRenderTest.java源代码。

方法是将标签呈现为图像,然后将图像呈现为Graphics对象。
https://stackoverflow.com/questions/7774960
复制相似问题