将图片插入JTextPane [英] Insert a picture into a JTextPane
问题描述
在我的记事本应用程序中,我正在尝试将图像添加到 JLabel
中,如同 JTextPane
点击 JMenuItem
,名为图片
。
In my notepad application, I am trying to add an image as if it were a JLabel
into a JTextPane
by clicking on a JMenuItem
called Picture
.
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
,我已经知道为什么会发生这种情况但是......我如何编写那行代码,这样我就可以做类似于<$ c $的事情了c> textPane.add(image)(因为我无法做到 textPane.add(StyleConstants.setIcon(def,createImageIcon(filename));
)还有另一个我应该写我的代码来正确执行吗?
The issue lies on Line 20 where there is a NullPointerException
, which I already know why this is happening but... How do I write that line of code so I could do something similar to textPane.add(image)
(since I can't do textPane.add(StyleConstants.setIcon(def, createImageIcon(filename));
)? Is there another I should write my code to execute this properly?
推荐答案
经过大量研究后我终于想出来了特别感谢这篇文章以及camickr's发布。
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);
}
}
}
这篇关于将图片插入JTextPane的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!