如何在MATLAB编辑器中以编程方式执行“折叠全部折叠”?

8

我已经在这个问题上挣扎了比我想承认的时间更长。

我正在尝试以编程方式执行用户单击“查看”>“折叠全部”按钮或右键单击编辑器窗口然后选择“代码折叠”>“折叠全部”时发生的相同Action

我尝试和发现的内容:

  • Action对应的String可以在enumcom.mathworks.mde.editor.ActionID中找到,为:'collapse-all-folds'
  • Action激活时,似乎会执行以下方法:org.netbeans.api.editor.fold.FoldUtilities.collapseAll(...)(因此有netbeans标签)。
  • 此代码允许我获取EditorActionActionManagerMatlabEditor的实例:

jEd = com.mathworks.mlservices.MLEditorServices.getEditorApplication.getActiveEditor;
jAm = com.mathworks.mde.editor.ActionManager(jEd);
jAc = com.mathworks.mde.editor.EditorAction('collapse-all-folds');

我的问题是我找不到一种方法来实际激活“Action”。
有什么想法/替代方案吗?
编辑1:在"这本书"中深入研究后,我认为我比以前更接近了(但还不够)。引用自该书的内容如下:

Java GUI组件通常使用ActionMap存储可运行的Actions,这些Actions由鼠标、键盘、属性或容器事件上的监听器调用。与对象方法不同,Actions不能直接由MATLAB调用。

然后解释了一种解决方法,大致涉及获取某种类型的Action对象;创建一个ActionEvent并使用ActionEvent作为参数调用ActionactionPerformed,如下所示:
import java.awt.event.*;
jEd = com.mathworks.mlservices.MLEditorServices.getEditorApplication.getActiveEditor;
jAm = com.mathworks.mde.editor.ActionManager(jEd);
jAc = jAm.getAction(com.mathworks.mde.editor.EditorAction('collapse-all-folds'));
jAe = ActionEvent(jAm, ActionEvent.ACTION_PERFORMED, '');
jAc.actionPerformed(jAe);

这段代码运行没有出错,但是好像什么也没做。我怀疑我在错误的对象上调用了 "ActionEvent" 和 "actionPerformed"("ActionManager" 可能与这个问题没有任何关系)。

P.S.

我知道有一个热键可以做到这一点(Ctrl + =),但这不是我要找的方法(除非有一个命令来模拟按下热键:)


也许@YairAltman会听到这个呼唤并回答。 - Sam Roberts
@Sam - 呵呵...不错的尝试 :) - Dev-iL
啊!谢谢热键!!这就是我要找的! - Pedro77
2个回答

3

经过无数次的挖掘、试验以及太多的错误 - 我终于做到了!

function FullyCollapseCurrentScript()

%// Get the relevant javax.swing.text.JTextComponent:
jTc = com.mathworks.mlservices.MLEditorServices ...
        .getEditorApplication.getActiveEditor.getTextComponent();
%// Get the FoldHierarchy for the JTextComponent:
jFh = org.netbeans.api.editor.fold.FoldHierarchy.get(jTc);
%// Finally, collapse every possible fold:
org.netbeans.api.editor.fold.FoldUtilities.collapseAll(jFh);

end

或者如果压缩成一个混乱的单一命令:
org.netbeans.api.editor.fold.FoldUtilities.collapseAll(...
org.netbeans.api.editor.fold.FoldHierarchy.get(com.mathworks. ...
mlservices.MLEditorServices.getEditorApplication.getActiveEditor. ...
getTextComponent()));

请注意,此操作仅适用于当前在编辑器中打开的脚本。

1
并不是完美的解决方案,但使用 java.awt.robot 模拟默认热键按下是可行的。 ...找到一种直接触发操作的方法会更好...
import java.awt.Robot;
import java.awt.event.*;
RoboKey = Robot;

jTextComp = com.mathworks.mlservices.MLEditorServices. ... 
        getEditorApplication.getActiveEditor.getTextComponent;


jTextComp.grabFocus()
drawnow;            %// give time for focus


if jTextComp.hasFocus()
    RoboKey.keyPress(KeyEvent.VK_CONTROL);
    RoboKey.keyPress(KeyEvent.VK_EQUALS);

    RoboKey.keyRelease(KeyEvent.VK_CONTROL);
    RoboKey.keyRelease(KeyEvent.VK_EQUALS);

    com.mathworks.mde.cmdwin.CmdWin.getInstance.grabFocus;  %// focus back to cmdwin

else
    warning('Failed to collapse folds: Editor could not take focus')
end

我在某个地方看到过这种解决方案(我相信是这里),但希望有更简洁的东西。 - Dev-iL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接