Home > Net >  How to show ImageIcons in JTextPane only vertically, one below the other?
How to show ImageIcons in JTextPane only vertically, one below the other?

Time:01-06

I'm getting BufferdImages from a device and converting them to ImageIcons and showing them in JTextPane.

public static void insertImage(BufferedImage img, JTextPane jTextPane){

    ImageIcon icon = new ImageIcon(img);
    jTextPane.insertIcon(icon);

}

My problem is that images are added one after another in one line and I have to scroll horizontally to see them. I want each new ImageIcon to go below the previous one, in other words, to add a new line after each ImageIcon.

I tried doing jTextPane.setText("\n"); after adding each image, but this only reset the whole jTextPane.

I need to show these images in a Swing application among some other data, and if someone has a better suggestion on what to use instead jTextPane for this purpose, please suggest it.

Thanks in advance.

CodePudding user response:

Here's how you can vertically align images in a JTextPane using the underlying StyledDocument. With this document, you can manually add line breaks at a position of your choice.

BufferedImage img1 = ...
BufferedImage img2 = ...

// add first image
jTextPane.insertIcon(img1);

// add line break at the end
StyledDocument doc = jTextPane.getStyledDocument();
doc.insertString(doc.getLength(), "\n" , null);

// add second image
jTextPane.insertIcon(img2);
  • Related