将图片插入JTextPane

时间:2011-12-30 02:05:41

标签: java image swing actionlistener jtextpane

在我的记事本应用程序中,我尝试通过点击名为JLabel的{​​{1}}将图像添加到JTextPane JMenuItem


Picture

问题在于第20行,其中有一个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; } } } ,我已经知道为什么会发生这种情况但是...我如何编写这行代码,以便我可以做类似于{{1}的操作(因为我做不到NullPointerException)?还有另一个我应该写我的代码来正确执行这个吗?

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

经过大量研究,我终于弄明白了!特别感谢this post以及camickr的帖子。


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