如果是Java2D的粉丝;但是为了在 Swing 组件和布局中充分利用 HTML,我鼓励您使用 @camickr 建议的组件方法。如有必要,可以使用 等文中看到的蝇量级渲染器方法,其中重复使用单个组件进行绘制。下面的示例是该技术的非常简化的轮廓,仅更改颜色和位置。JTable
附录:更新示例;另请参阅 CellRendererPane
和 Make your apps fly: Implement Flyweight 以提高性能。
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();
}
});
}
}