How to insert image in JTextPane

We've worked with text till date. Let's now move to images. Here is a tutorial on inserting an image in JTextPane in the easiest way that you could never forget. You don't need to think that you need to write tens of lines of code for this, we've got a method and it will do the job for us. Here we go.

Inserting an Image

insertIcon(Icon icon): This method is present in javax.swing.JTextPane class and takes javax.swing.Icon class object. This method inserts an image at the current caret position if there is no selection, else will replace the selection.


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class InsertImageInJTextPane extends JFrame
{
private JTextPane jt;
private JScrollPane js;
private JMenuItem insert;
private JMenu menu;
private JMenuBar menuBar;

    public InsertImageInJTextPane()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Insert image in JTextPane");
        setSize(400,400);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        jt=new JTextPane();
        js=new JScrollPane(jt);
        add(js);
       
        menuBar=new JMenuBar();
        menu=new JMenu("Menu");
       
        insert=new JMenuItem("Insert an image..");
        menu.add(insert);   
       
        insert.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                insertActionPerformed();
            }
        });
       
        menuBar.add(menu);
        setJMenuBar(menuBar);
       
        // Center the JFrame
        setLocationRelativeTo(null);
    }
   
    private void insertActionPerformed()
    {
        JFileChooser jf=new JFileChooser();
       
        // Show open dialog
        int option=jf.showOpenDialog(this);
       
            // If user chooses to insert..
            if(option==JFileChooser.APPROVE_OPTION)
            {
                File file=jf.getSelectedFile();
                    if(isImage(file))
                    {
                        // Insert the icon
                        jt.insertIcon(new ImageIcon(file.getAbsolutePath()));
                    }
                    else
                    // Show an error message, if not an image
                    JOptionPane.showMessageDialog(this,"The file is not an image.","Not Image",JOptionPane.ERROR_MESSAGE);
            }
    }
   
    private boolean isImage(File file)
    {
        String name=file.getName();
            return name.endsWith(".jpg") || name.endsWith(".png") || name.endsWith(".jpeg") || name.endsWith(".gif");
    }
   
    public static void main(String args[])
    {
        new InsertImageInJTextPane();
    }
}

Output of InsertImageInJTextArea

Inserting an image in JTextArea using insertIcon


Posted by at on

Tags: Swing Components,