By George Casttrey

2011-10-15 00:42:07 8 Comments

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(){

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

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?


@trashgod 2011-10-15 06:24:19

If a fan of Java2D; but to get the most leverage from HTML in Swing components and layouts, I'd encourage you to use the component approach suggested by @camickr. If necessary, you can use the flyweight renderer approach seen in JTable, et al, in which a single component is used repeatedly for drawing. The example below is a very simplified outline of the technique, changing only the color and location.

Addendum: Updated example; see also CellRendererPane and Make your apps fly: Implement Flyweight to improve performance.

enter image description here

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 */
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() {
        dim = renderer.getPreferredSize();

    protected void paintComponent(Graphics 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.setSize(dim.width * N, dim.height * (N + 1));

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PaintComponentTest().display();

@George Casttrey 2011-10-15 14:27:24

thank you very much for the help. I've found out another way to do this without needing the CellRendererPane. (Take a look on my answer post).

@trashgod 2011-10-15 15:12:14

You're welcome. CellRendererPane offers a few convenient optimizations for buffering and validation that may yet prove useful going forward.

@George Casttrey 2011-10-15 14:19:02

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() {

    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);
        //the fontMetrics stringWidth and height can be replaced by
        //getLabel().getPreferredSize() if needed
        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.

@Evgeni Sergeev 2018-10-09 19:43:25

As noted here, it may be necessary to getLabel().setSize(getLabel().getPreferredSize()) if the JLabel has never been added under a Frame that has been pack()ed (or equivalent).

@Andrew Thompson 2011-10-15 04:19:52

As others have commented, Swing components support HTML 3.2 and basic styles.

For details on how to leverage that ability in the paintComponent(Graphics) method, see the source on this thread.

The approach is to render the label to an image, then render the image to the Graphics object.

@George Casttrey 2011-10-15 14:24:35

I've found out a way to paint the htmlString using JLabel but without the need to render an image (take a look on my post). Thank you very much for the help.

@jpalm 2011-10-15 02:45:13

There isn't an easy way to render HTML to paint with Graphics, go with a JLabel.

However, there is an interesting way to accomplish this by creating a JLabel with HTML and painting it's graphics to the component:

private JLabel label;

public MyComponent() {
    label = new JLabel("Before Red");

public void repaint(Graphics g){
    g = label.getGraphics();

The easiest way to accomplish this would be to set a font for your graphics, for example:

public void repaint(Graphics g){    
    Font f = new Font("Courier", Font.BOLD, 12);
    g.drawString("Bolded Courier", 5, 15);

@COD3BOY 2011-10-15 02:40:17

This is not the way to implement.

The drawString(String str, int x, int y) only draws the text given by the specified string, using this graphics context's current font and color.

You can get more information for your problem from here, How to Use HTML in Swing Components

@George Casttrey 2011-10-15 14:29:41

thank you for the answer, it helped me to go in the right way.

@camickr 2011-10-15 02:39:35

The answer to your question is that HTML is not supported.

The easy solution is to use Swing components and lay them out properly.

If you want to do it yourself then you need to manipulate the Font that you use for the drawString() method. You can use a Font with italics, bold etc.

@George Casttrey 2011-10-15 14:28:15

Thank you very much for the answer, it helped me thinking the right way.

@Michał Šrajer 2011-10-15 00:48:13

Use JLabel as your base class. Graphics.drawString() can only... draw a string.

@George Casttrey 2011-10-15 01:02:41

My component doesn't just draw a html string, there's plenty of other drawing operations which i didn't want to show in the sample code just to focus on the real problem. I know that JLabel and all other Swing components which are holding text do support the html format.<br/> Im just wondering if there's any way to render html texts through a Graphics instance.

@George Casttrey 2011-10-15 14:30:08

Thank you for the helpful answer.

Related Questions

Sponsored Content

10 Answered Questions

[SOLVED] Why does HTML think “chucknorris” is a color?

5 Answered Questions

[SOLVED] What is the purpose of the "role" attribute in HTML?

32 Answered Questions

[SOLVED] How to create an HTML button that acts like a link?

28 Answered Questions

[SOLVED] HTML 5: Is it &lt;br&gt;, &lt;br/&gt;, or &lt;br /&gt;?

  • 2009-12-22 13:39:08
  • Eikern
  • 1384737 View
  • 2060 Score
  • 28 Answer
  • Tags:   html

28 Answered Questions

[SOLVED] Redirect from an HTML page

23 Answered Questions

[SOLVED] What are valid values for the id attribute in HTML?

  • 2008-09-16 09:08:52
  • Mr Shark
  • 449239 View
  • 2025 Score
  • 23 Answer
  • Tags:   html id

27 Answered Questions

[SOLVED] How can I set the default value for an HTML <select> element?

  • 2010-08-19 01:10:51
  • Jichao
  • 2587489 View
  • 1483 Score
  • 27 Answer
  • Tags:   html html-select

26 Answered Questions

[SOLVED] Retrieve the position (X,Y) of an HTML element relative to the browser window

1 Answered Questions

[SOLVED] paint on a container being added to jcomponent

Sponsored Content