在我的记事本应用程序中,我试图通过单击 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/