Insert a picture into a JTextPane

别来无恙 提交于 2019-12-05 20:47:40

You can add components or icons to a text pane:

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

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);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!