感谢 Yair Altman在undocumentedmatlab.com上发表的出色文章,我尝试使用丰富的编辑框和底层 java 组件来实现 GUI 日志程序。这是代码的简化版本:
首先是创建面板的代码
function jEditbox = logPanel()
hFig = figure('color', 'w');
hPanel = uipanel(hFig);
% Prepare the log editbox
hLogPanel = uicontrol('style', 'edit', 'max', 5, 'Parent', hPanel, ...
'Units', 'normalized', 'Position', [0, 0.2, 1, 0.8], 'Background', 'w');
% Get the underlying Java editbox, which is contained within a scroll-panel
jScrollPanel = findjobj(hLogPanel);
try
jScrollPanel.setVerticalScrollBarPolicy(jScrollPanel.java.VERTICAL_SCROLLBAR_AS_NEEDED);
jScrollPanel = jScrollPanel.getViewport();
catch %#ok<CTCH>
% may possibly already be the viewport, depending on release/platform etc.
end
jEditbox = handle(jScrollPanel.getView, 'CallbackProperties');
% Prevent user editing in the log-panel
jEditbox.setEditable(false);
% Set-up a Matlab callback function to handle hyperlink clicks
set(jEditbox,'HyperlinkUpdateCallback',@linkCallbackFcn);
% Ensure we have an HTML-ready editbox
HTMLclassname = 'javax.swing.text.html.HTMLEditorKit';
if ~isa(jEditbox.getEditorKit, HTMLclassname)
jEditbox.setContentType('text/html');
end
end
然后是日志记录代码:
function logMessage(jEditbox, text)
% newText = [iconTxt, msgTxt ' '];
text = [text '<br/>'];
% Place the HTML message segment at the bottom of the editbox
currentHTML = char(jEditbox.getText);
newHTML = strrep(currentHTML, '</body>', text);
jEditbox.setText(newHTML);
endPosition = jEditbox.getDocument.getLength;
jEditbox.setCaretPosition(endPosition);
end
我有两个问题:
在需要大量记录消息(即 > 500)的应用程序中存在重大性能问题。使用分析器和以下代码(请注意,我已修改
why
为返回字符串而不是打印到命令行),我发现瓶颈是setText()
. 谁能解释图中的尖峰是什么?h = logPanel(); n = 1e3; time = nan(n, 1); profile on for i = 1:n tic logMessage(h, why) time(i) = toc; end profile viewer avgTime = mean(time); figure('color', 'w') bar(time) hold on plot([0, n], avgTime*ones(1, 2), '-k', 'LineWidth', 2) hold off title(sprintf('Average Time = %f [s]', avgTime));
如果我在
pause(0.1)
之后添加一个toc
,那么图表看起来像这里发生了什么?
这会导致一个非常“华丽”的日志面板。每次我写一条消息时,内容都会闪烁,因为它滚动到顶部然后又回到底部。再一次,这个缺陷是由于
setText()
,它迫使插入符号位于文档的开头。
我正在寻找这些问题中的任何一个的解决方案,最好两者兼而有之。