Why can't I use Java in startup.m?

I have multiple monitors, and in my startup.m script, I'm trying to find out which one the MATLAB GUI is in (because I want to set the default figure location to the other monitor). This answer tells me to use the following Java object to get the location of the MATLAB GUI:
pt = com.mathworks.mlservices.MLEditorServices.getEditorApplication.getActiveEditor.getComponent.getRootPane.getLocationOnScreen;
This works great, except when I put it in my startup.m script. I get this warning on the line of code shared above when I start MATLAB, and the rest of my startup.m script doesn't run:
Warning: Executing startup failed in matlabrc.
This indicates a potentially serious problem in your MATLAB setup, which should
be resolved as soon as possible. Error detected was:
MATLAB:structRefFromNonStruct
Dot indexing is not supported for variables of this type.
So is Java not available during MATLAB startup? If not, is there another way to determine which monitor MATLAB is open in?
I'm using MATLAB 9.4.0.813654 (R2018a) on Windows.

 Accepted Answer

Jan
Jan on 23 Apr 2021
Edited: Jan on 23 Apr 2021
I assume, that Java is not running completely at this time. I'm working with different Matlab versions at the same time and insert the version number as title of the Command Window. This does not work during startup.m runs also.
The solution is easy: Just wait some seconds:
% Insert this in startup.m:
if usejava('desktop')
timerH = timer('TimerFcn', @SetCWTitle, 'ExecutionMode', 'SingleShot', ...
'StartDelay', 5);
start(timerH);
end
% And the callback:
% ******************************************************************************
function SetCWTitle(TimerH, EventData) %#ok<INUSD>
% Get main frame of command window:
matlabV = [100, 1] * sscanf(version, '%d.', 2);
if matlabV >= 700
Name = ['Matlab', version('-release')];
mainFrame = com.mathworks.mde.desk.MLDesktop.getInstance.getMainFrame;
mainFrame.setTitle(Name);
end
stop(TimerH);
delete(TimerH);
end
You can try to insert your code equivalently.
An alternative is to define a DefaultFigureCreationFcn, which determines the position of the GUI at run time.
By the way, you mention the position of "MATLAB GUI" and use the position of the editor. The Main window might be an option also. The command window can be undocked also. So maybe it is easier to mange the setup dynamically.

1 Comment

Thanks Jan, that works! I had tried pausing before, but apparently I didn't pause for long enough.

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2018a

Asked:

on 23 Apr 2021

Commented:

on 23 Apr 2021

Community Treasure Hunt

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

Start Hunting!