我想实现一个JTextPane
来编辑文本,使用我从系统拖放到JTextPane
的图像。我试图通过使用JTextPane
作为超类和DropTargetListener
作为接口来实现它。但是当我试图读取我的InputStream时,我得到一个NullPointerException
。请帮忙。
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JTextPane;
public class JTextTest extends JTextPane implements DropTargetListener {
private static final long serialVersionUID = 1L;
public JTextTest() {
new DropTarget(this, this);
this.setDragEnabled(true);
}
@Override
public void dragEnter(DropTargetDragEvent arg0) {
}
@Override
public void dragExit(DropTargetEvent arg0) {
}
@Override
public void dragOver(DropTargetDragEvent arg0) {
}
@Override
public void drop(DropTargetDropEvent dropTargetDropEvent) {
System.out.println("Drop event");
Transferable transferable = dropTargetDropEvent.getTransferable();
for (DataFlavor d : transferable.getTransferDataFlavors()) {
if (d.isRepresentationClassInputStream()) {
dropTargetDropEvent
.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
try {
InputStream is = new BufferedInputStream(
(InputStream) transferable.getTransferData(d));
ImageIcon image = new ImageIcon(ImageIO.read(is));
this.insertIcon(image);
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
dropTargetDropEvent.rejectDrop();
}
}
dropTargetDropEvent.getDropTargetContext().dropComplete(true);
}
@Override
public void dropActionChanged(DropTargetDragEvent arg0) {
}
}
答案 0 :(得分:1)
尝试使用此代码段,
ImageIcon image = new ImageIcon(ImageIO.read(createImageInputStream(is)));
ImageIO.read()需要File,ImageInputStream,InputStream或URL并注意到在处理图片时,大多数NullPointerException
当有问题(更具体地说,读取图像返回null)与图像,图像源或从该源读取时抛出。