How to save in a drag and drop

2 views (last 30 days)
axel rose
axel rose on 26 Dec 2020
Answered: Jan on 30 Dec 2020
function drag_drop
dragging = [];
orPos = [];
f = figure('WindowButtonUpFcn',@dropObject,'units','normalized','WindowButtonMotionFcn',@moveObject);
tmp = text(0.35,0.35,'Room','VerticalAlignment','bottom');
a = rectangle('position',[0.35, 0.35, 0.35, 0.35],'FaceColor','w','ButtonDownFcn',@dragObject,'UserData',tmp);
tmp = text(0.1,0.1,'StudyTable','VerticalAlignment','bottom');
b = rectangle('position',[0.1, 0.1, 0.1, 0.1],'FaceColor','y','ButtonDownFcn',@dragObject,'UserData',tmp);
tmp = text(0.1,0.1,'CoffeeTable','VerticalAlignment','bottom');
c = rectangle('position',[0.1, 0.1, 0.1, 0.1],'FaceColor','y','ButtonDownFcn',@dragObject,'UserData',tmp);
set(gca,'XLim',[0,1],'YLim',[0,1])
function dragObject(hObject,eventdata)
dragging = hObject;
orPos = get(gcf,'CurrentPoint');
end
function dropObject(hObject,eventdata)
if ~isempty(dragging)
newPos = get(gcf,'CurrentPoint');
posDiff = newPos - orPos;
rectpos = get(dragging,'Position') + [posDiff(1:2) 0 0];
set(dragging,'Position',rectpos);
set(dragging.UserData,'Position',rectpos(1:3));
dragging = [];
end
end
function moveObject(hObject,eventdata)
if ~isempty(dragging)
newPos = get(gcf,'CurrentPoint');
posDiff = newPos - orPos;
orPos = newPos;
rectpos = get(dragging,'Position') + [posDiff(1:2) 0 0];
set(dragging,'Position',rectpos);
set(dragging.UserData,'Position',rectpos(1:3));
end
end
end
The code above is a drag and drop. Im able to move the items around in the space but i cannot save it. Therefore, if i run it again, the items will go back to their original positions regardless of what position i dragged it to . How do i make the drag and drop savable so that when i run it again it will go back to how i previously left the items in matlab.

Answers (1)

Jan
Jan on 30 Dec 2020
There are some problems with the movement: The object does not move exactly as the mouse.
But you are asking for saving the positions. You can either save the figure by the savefig command. Or create an own save function, which store the positions of the objects. Then loading the file does restore the positions instead of creating new objects.
function drag_drop(Command)
switch Commad
case 'create'
... your code comes here
case 'save'
savefig(f, fullfile(tempdir, 'myDragDropFigure.fig'));
delete(f);
case 'load'
f = openfig(fullfile(tempdir, 'myDragDropFigure.fig'));
end

Categories

Find more on Simultaneous and Synchronized Operations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!