anon
anon

Reputation:

Insert a picture into a JTextPane

In my notepad application, I am trying to add an image as if it were a JLabel into a JTextPane by clicking on a JMenuItem called Picture.


private class Picture implements ActionListener
{
    public void actionPerformed(ActionEvent event)
    {
        fc = new JFileChooser();
        FileNameExtensionFilter picture = new FileNameExtensionFilter("JPEG files (*.jpg)", "jpg");
        fc.setFileFilter(picture);
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

        if (fc.showDialog(Notepad.this, "Insert")!=JFileChooser.APPROVE_OPTION)  return;
        filename = fc.getSelectedFile().getAbsolutePath();

        // If no text is entered for the file name, refresh the dialog box
        if (filename==null) return;

        // NullPointerException
        textArea.insertIcon(createImageIcon(filename));
    }

    protected ImageIcon createImageIcon(String path) 
    {
        java.net.URL imgURL = Notepad.class.getResource(path);

        if (imgURL != null) 
        {
            return new ImageIcon(imgURL);
        } 

        else 
        {
            JOptionPane.showMessageDialog(frame, "Could not find file: " + path);
            return null;
        }
    }
}

The issue lies on Line 20 where there is a NullPointerException, which I already know why this is happening but... How do I write that line of code so I could do something similar to textPane.add(image) (since I can't do textPane.add(StyleConstants.setIcon(def, createImageIcon(filename));)? Is there another I should write my code to execute this properly?

Upvotes: 3

Views: 7115

Answers (2)

anon
anon

Reputation:

After much research I have finally figured it out! Special thanks to this post as well as camickr's post.


private class Picture implements ActionListener
{
    public void actionPerformed(ActionEvent event)
    {
        fc = new JFileChooser();
        FileNameExtensionFilter picture = new FileNameExtensionFilter("JPEG files (*.png)", "png");
        fc.setFileFilter(picture);
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

        if (fc.showDialog(Notepad.this, "Insert")!=JFileChooser.APPROVE_OPTION)  return;
        filename = fc.getSelectedFile().getAbsolutePath();

        // If no text is entered for the file name, refresh the dialog box
        if (filename==null) return;

        try 
        {
            BufferedImage img = ImageIO.read(new File(filename));
            ImageIcon pictureImage = new ImageIcon(img);
            textArea.insertIcon(pictureImage);
        } 

        catch (IOException e) 
        {
            JOptionPane.showMessageDialog(frame, "Could not find file: " + filename);
        }
    }
}

Upvotes: 2

camickr
camickr

Reputation: 324088

You can add components or icons to a text pane:

textpane.insertIcon(...);
textPane.insertComponent(...);

Upvotes: 4

Related Questions