javahtmlswinggraphics2djcomponent

Swing HTML drawString


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);
     }
 }

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?


Solution

  • 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.