SWT 拖拽打开文件

在ApplicationWorkbenchWindowAdvisor.java中的postWindowOpen()函数内加入以下代码

		DropTarget target = new DropTarget(getWindowConfigurer().getWindow()
				.getShell(), DND.DROP_DEFAULT | DND.DROP_MOVE | DND.DROP_COPY
				| DND.DROP_LINK);
		target.setTransfer(new Transfer[] { FileTransfer.getInstance() });
		target.addDropListener(new DropTargetAdapter() {

			public void drop(DropTargetEvent e) {
				try {
					IWorkbenchPage page = PlatformUI.getWorkbench().
			        getActiveWorkbenchWindow().getActivePage();
					String[] paths=(String[]) e.data;
					if(paths.length!=1){
						//only one
					}else{
						for (String path : paths) {
							page.openEditor(new FileEditorInput(path), "editor_ID");
						}
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});

 新建FileEditorInput.java

public class FileEditorInput implements IEditorInput{

	File file;
	
	public FileEditorInput(String path) {
		super();
		file=new File(path);
	}

	@Override
	public boolean exists() {
		// TODO Auto-generated method stub
		return file.exists();
	}

	@Override
	public ImageDescriptor getImageDescriptor() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return exists()?file.getName():"error";
	}

	@Override
	public IPersistableElement getPersistable() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getToolTipText() {
		// TODO Auto-generated method stub
		return exists()?file.getName():"error";
	}

	@Override
	public Object getAdapter(Class adapter) {
		// TODO Auto-generated method stub
		return null;
	}
}
 

你可能感兴趣的:(打开文件)