java - 将图片插入 JTextPane

标签 java image swing actionlistener jtextpane

在我的记事本应用程序中,我试图通过单击 JMenuItem 将图像添加到 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,我已经知道为什么会发生这种情况,但是......我该如何编写那行代码,以便我可以做类似 的事情code>textPane.add(image)(因为我不能做 textPane.add(StyleConstants.setIcon(def, createImageIcon(filename));)?还有我应该写的我的代码可以正确执行吗?

最佳答案

您可以将组件或图标添加到文本 Pane :

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

关于java - 将图片插入 JTextPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8675482/

相关文章:

swift - 在 CGContext 中重新创建 UIImageView 的 CGAffineTransform

html - 未从 Dropbox 检索图像

java - 字体增大时 JPanel 问题

java - 如何使用 swing 创建可定制的用户界面

java - 为什么 Jtable 中行高自动调整不起作用

java - 使用 volatile 变量停止线程

Java-使用另一个文件中的变量

java - 编译器错误 “cannot be applied”?

Android MediaStore Crop 功能,如何使选择箭头始终可见?

java - JPA:删除具有相关子项的父项