Search code examples
javaimageswingjtextpane

Display selected image in a JTextPane


How can I show an image I have selected from the file chooser in a my textpane (jTextPaneBody)? This is the code I have so far but I don't know what else needs to be added in order to achieve this.

private void jButtonAttachActionPerformed(java.awt.event.ActionEvent evt) {                                              
        JFileChooser jc = new JFileChooser();
        jc.setDialogType(JFileChooser.OPEN_DIALOG);
        jc.showOpenDialog(null);
        File f = jc.getSelectedFile();
    } 

Solution

  • Start by taking a look at How to Use Labels and Reading/Loading an Image

    BufferedImage img = ImageIO.read(f);
    JLabel label = new JLabel(new ImageIcon(img));
    

    Then you can use JTextPane#insertIcon or JTextPane#insertComponent to physically add the image based on your needs