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?