我尝试实现与您相同的功能,并在尝试获取可传输数据时陷入相同的异常。
目前还不清楚是否getTransferable
由于默认而失败FlavorMap
实例化于%matlabroot%\sys\java\jre\...\lib\flavormap.properties
(如指出亚尔奥特曼的书 http://undocumentedmatlab.com/books/matlab-java在拖放部分)或者出于其他一些奇怪的原因。无论如何我遇到了这个dnd控制 https://fr.mathworks.com/matlabcentral/fileexchange/53511-drag---drop-functionality-for-java-gui-components对象上文件交换 https://fr.mathworks.com/matlabcentral/fileexchange/通过直接管理 java 端的可传输数据,这对我们的目的来说就像一个魅力。
我从中得到启发,在上面编写了我自己的 matlab 代理java.awt.dnd.DropTarget https://docs.oracle.com/javase/7/docs/api/java/awt/dnd/DropTarget.html它更通用,更接近其 java 实现对等体(即它的工作方式与 java 完全相同)DropTarget
对象(除了所有数据类型已转换为更标准和方便的 matlab 类型)。
您可以从这里下载我的实现:
- GitHub: 删除监听器 https://github.com/CitizenInsane/DropListener
- 文件交换:删除监听器 https://fr.mathworks.com/matlabcentral/fileexchange/64776-droplistener
这里有一些使用示例来完成您需要的操作(从文件资源管理器中放入 matlab 轴):
%
% PURPOSE:
%
% Show how to add drop support from file explorer to some matlab axis
%
% SYNTAX:
%
% [] = DropListenerDemo();
%
% USAGE:
%
% Simply drop files from file explorer into displayed axis.
%
%%
function [] = DropListenerDemo()
%[
% Create a figure with some axis inside
fig = figure(666); clf;
axes('Parent', fig);
% Get back the java component associated to the axis
% NB1: See §3.7.2 of Undocumented Secrets of Matlab Java Programming
% NB2: or use findjobj, or javaObjectEDT for drop support onto other component types
jFrame = get(handle(fig), 'JavaFrame');
jAxis = jFrame.getAxisComponent();
% Add listener for drop operations
DropListener(jAxis, ... % The component to be observed
'DropFcn', @(s, e)onDrop(fig, s, e)); % Function to call on drop operation
%]
end
function [] = onDrop(fig, listener, evtArg) %#ok<INUSL>
%[
% Get back the dropped data
data = evtArg.GetTransferableData();
% Is it transferable as a list of files
if (data.IsTransferableAsFileList)
% Do whatever you need with this list of files
msg = sprintf('%s\n', data.TransferAsFileList{:});
msg = sprintf('Do whatever you need with:\n\n%s', msg);
uiwait(msgbox(msg));
% Indicate to the source that drop has completed
evtArg.DropComplete(true);
elseif (data.IsTransferableAsString)
% Not interested
evtArg.DropComplete(false);
else
% Not interested
evtArg.DropComplete(false);
end
%]
end
该对象还支持捕获DragEnter
, DragOver
, DropActionChanged
, DragExit
事件,以便您可以调整拖动操作的各个方面。不费吹灰之力,它还可以扩展为支持图像拖动或其他数据类型的拖动。
希望您会喜欢它,并且您会发现它足够通用,可以考虑其他用途。