在我的记事本应用程序中,我尝试添加图像,就好像它是JLabel
into a JTextPane
通过单击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
,我已经知道为什么会发生这种情况,但是......我如何编写该行代码,以便我可以做类似的事情textPane.add(image)
(因为我做不到textPane.add(StyleConstants.setIcon(def, createImageIcon(filename));
)?我还应该编写另一个代码来正确执行它吗?
您可以将组件或图标添加到文本窗格:
textpane.insertIcon(...);
textPane.insertComponent(...);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)