将图片插入JTextPane

在我的记事本应用程序中,我试图通过单击名为PictureJMenuItem将图像添加到JTextPane ,就好像它是JLabel


 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; } } } 

问题出在第20行,其中有一个NullPointerException ,我已经知道为什么会发生这种情况但是……我如何编写那行代码,这样我就可以做类似于textPane.add(image)事情了(因为我可以’做textPane.add(StyleConstants.setIcon(def, createImageIcon(filename)); )?还有另一个我应该写我的代码来正确执行吗?

您可以在文本窗格中添加组件或图标:

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

经过大量的研究,我终于弄明白了! 特别感谢这篇文章以及camickr的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); } } }