Search code examples
javaswingtextgraphicsawt

How can I align text in a BufferedImage as columns?


I am using BufferedImage and Graphics2D to generate a GIF image, but I am struggling to have the layout like in the picture below. I am not even sure if it's possible at all.

The GIF will be animated and the values in Heading3 will change. I've created the code to generate the GIF, but I can't really get this layout. I looked into TextLayout and LineBreakMeasurer, but am not getting the desired o/p. The text should scale based on the image size (which I've got working), but that's key as well.

Any tips?

enter image description here


Solution

  • HTML can be used in Swing components which support rich text, like JLabel. The label can be painted onto an image.

    This HTML/CSS should do the trick.

    .num {
        color: rgb(0,0,255);
    }
    td {
        text-align: center;
        padding: 10px;
    }
    <table border=0 cellspacing=0>
    <tr>
    <td>
    HEADING1<br>
    <span class='num'>103</span>
    </td>
    <td>
    HEADING2<br>
    <span class='num'>76</span>
    </td>
    <td>
    HEADING3<br>
    <span class='num'>64</span>
    </td>
    </tr>

    Edit 1:

    Can't use HTML as I have custom fonts and it won't use the fonts correctly.

    To use a custom font in HTML, it needs to be (imported and) registered with the GraphicsContext as shown in this answer.