将图像从文件夹拖放到JTextPane

时间:2011-11-03 21:08:55

标签: java swing drag-and-drop wysiwyg

我想实现一个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) {
}
}

1 个答案:

答案 0 :(得分:1)

尝试使用此代码段,

ImageIcon image = new ImageIcon(ImageIO.read(createImageInputStream(is)));

ImageIO.read()需要FileImageInputStreamInputStreamURL并注意到在处理图片时,大多数NullPointerException当有问题(更具体地说,读取图像返回null)与图像,图像源或从该源读取时抛出。