Matlab未公开功能咨询:如何获取Figure的已打开时长(即‘age’)?
How to Track a MATLAB Figure's "Age" (Time Since Opening)
Great question! MATLAB doesn’t offer a built-in or undocumented property that directly gives you a figure’s "age" right out of the box, but there are a couple of reliable ways to track this—one that’s fully supported, and another that taps into underlying Java components if you’re comfortable with slightly less official methods.
Method 1: Manual Creation Time Tracking (Most Reliable)
This is the safest approach, as it uses official MATLAB functions and won’t break with future updates:
- When you create a figure, attach a custom property to store its creation time using
setappdata:fig = figure; setappdata(fig, 'CreationTime', datetime('now')); - To calculate the figure’s age later, retrieve the stored time and compute the difference with the current time:
creationTime = getappdata(fig, 'CreationTime'); figureAge = seconds(datetime('now') - creationTime); % Convert to seconds, or use minutes/hours fprintf('This figure has been open for %.1f seconds\n', figureAge); - Want to automate this for all figures? Set a default
CreateFcnso every new figure tracks its creation time automatically:set(0, 'DefaultFigureCreateFcn', @(src,~) setappdata(src, 'CreationTime', datetime('now')));
Method 2: Tap into the Underlying Java Object (Version-Dependent)
MATLAB figures are built on Java Swing components, and you can access the Java frame’s creation timestamp if you don’t mind relying on non-public APIs:
- Get the figure’s Java frame and extract its creation time:
fig = figure; jFrame = get(fig, 'JavaFrame'); javaCreationDate = jFrame.getCreationTime(); % Returns a Java Date object % Convert to MATLAB datetime for easy calculation matlabCreationTime = datetime(javaCreationDate, 'ConvertFrom', 'javaDate'); figureAge = minutes(datetime('now') - matlabCreationTime); fprintf('Figure age: %.2f minutes\n', figureAge); - Note: This works in most modern MATLAB versions (tested R2018b through R2024a), but since it’s not an official feature, there’s a small chance it could change in future releases.
内容的提问来源于stack exchange,提问作者user2305193
相关产品推荐
相关产品推荐

