Is there a way to make multiline JLabel text flow around the icon?

Tags: , ,



Currently in my project I have multiple JLabels each with their own text and icon

The problem I have is that the icon take a whole left side to it self

The effect I’m trying to achieve is to make the text flow around the icon

enter image description here

Is this effect possible with JLabel? if not, is it possible with any other component?

Answer

If this is a JLabel and not a JTextArea where the text is editable I would go with an HTMLed JLabel instead of a JEditorPane.

public static void main(String[] args) throws Exception {
    String imageUrl = "https://d1nhio0ox7pgb.cloudfront.net/_img/g_collection_png/standard/512x512/person.png";
    Image sourceImage = ImageIO.read(new URI(imageUrl).toURL()).getScaledInstance(25, 25,
            Image.SCALE_SMOOTH);

    //Write the image to disk locally
    File fileWithImage = File.createTempFile("myicon", ".png");
    fileWithImage.deleteOnExit();

    ImageIO.write(toBufferedImage(sourceImage), "png", fileWithImage);

    String lorem = "Lorem Ipsum is simply dummy text of the printing<br>"
            + " and typesetting industry. Lorem Ipsum has been the industry's<br>"
            + " standard dummy text ever since the 1500s, when an unknown printer<br>"
            + " took a galley of type and scrambled it to make a type specimen book.<br>"
            + " It has survived not only five centuries, but also the leap into electronic<br>"
            + " typesetting, remaining essentially unchanged. It was popularised in the 1960s<br>"
            + " with the release of Letraset sheets containing Lorem Ipsum passages ";
    String imgTag = "<img src="" + fileWithImage.toURI() + "">";

    final String htmlText = "<html>" + imgTag + " " + lorem;

    JOptionPane.showMessageDialog(null, new JLabel(htmlText));
}

public static BufferedImage toBufferedImage(Image img) {
    if (img instanceof BufferedImage) {
        return (BufferedImage) img;
    }

    BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();

    return bimage;
}

Run the above example. You will get as result the following image:

enter image description here

The image conversions depends on how you have the icons but the idea is this. Write the image into a temp file, make it an URI and add it as HTML text to the label.



Source: stackoverflow