logo
22.1
search
No matching documents found.
list
search
No matching documents found.
logo
Please be aware that there is newer version of documentation available for Webswing. Documentation 24.1

Drag & Drop

Webswing supports drag & drop functionality between swing components, drag & drop upload to file chooser and direct drag & drop of file from local system to swing component.

File chooser upload

To upload a file using drag & drop to a file chooser, simply open file chooser and drop a file from local file system to the marked area. Note that transparentFileSave config should be false.

File chooser upload

Direct drag & drop

To use direct drag & drop you first need to register a swing component that should receive the uploaded file. Use WebswingApi method to do this:

if (WebswingUtil.isWebswing()) {
	WebswingApi api = WebswingUtil.getWebswingApi();
	api.registerDropComponent(pic1);
}

The registered component must have a valid TransferHandler:

pic1.setTransferHandler(picHandler);

This is an example of a simple TransferHandler:

class PictureTransferHandler extends TransferHandler {

	private static List<DataFlavor> supportedFlavors = Arrays.asList(DataFlavor.javaFileListFlavor);

	public boolean importData(JComponent c, Transferable t) {
		if (canImport(c, t.getTransferDataFlavors())) {
			if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
				try {
					List<File> fileList = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
					if (fileList != null && !fileList.isEmpty()) {
						File droppedFile = fileList.get(0);
						return true;
					}
				} catch (IOException | UnsupportedFlavorException e) {
					// log
				}
			}
		}
		return false;
	}

	public boolean canImport(JComponent c, DataFlavor[] flavors) {
		for (int i = 0; i < flavors.length; i++) {
			if (supportedFlavors.contains(flavors[i])) {
				return true;
			}
		}
		return false;
	}

}

Direct drag & drop