【问题标题】:How can I determine if an edit box is overflowing (Matlab GUI)?如何确定编辑框是否溢出(Matlab GUI)?
【发布时间】:2015-11-09 17:42:05
【问题描述】:

我正在尝试创建一个文本框,一旦框满或溢出,字体就会调整大小。

除了将字体类型设置为固定宽度,并手动计算每种字体大小适合多少个字符之外,是否有自动/程序化的方式来执行此操作?

【问题讨论】:

    标签: matlab user-interface


    【解决方案1】:

    我找到了解决办法:

    对于静态文本框,可以使用“范围”UI 属性 (http://www.mathworks.com/help/matlab/ref/uicontrol-properties.html#property_extent) 来获取文本框的首选大小。

    不幸的是,对于编辑框,这将返回当前可见大小而不是首选大小 (Text 'Extent' property doesn't contain the correct size)。可以通过调用 java UI 调用来获得首选大小(Matlab 组件只是(大部分?)包装的 java swing 组件)。使用findjobj函数(http://www.mathworks.com/matlabcentral/fileexchange/14317-findjobj-find-java-handles-of-matlab-graphic-objects)获取编辑框的java句柄,获取框的首选大小。

    实现自动字体大小调整的代码(使用仍然适合整个字符串的最大字体大小):

    % --- Executes on key press with focus on edit1 and none of its controls.
    function edit1_KeyPressFcn(hObject, eventdata, handles)
    % hObject    handle to edit1 (see GCBO)
    % eventdata  structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL)
    %   Key: name of the key that was pressed, in lower case
    %   Character: character interpretation of the key(s) that was pressed
    %   Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
    % handles    structure with handles and user data (see GUIDATA)
    H = hObject;
    position = get(H,'Position');
    width = position(3);
    javaH = findjobj(H);
    for FontSize = 48:-2:12
        javaH.setFont(javaH.getFont().deriveFont(FontSize));
        prefWidth = javaH.getPreferredSize.getWidth;
        if prefWidth < width 
            break; % Escape loop: for FontSize
        end
    end
    

    我使用 java 方法更改字体大小,因为我注意到在使用 Matlab set(H,'FontSize',FontSize) 调用时首选宽度调用会不正确(延迟 1 次迭代?)。

    【讨论】:

      猜你喜欢
      • 2010-10-21
      • 2020-12-16
      • 1970-01-01
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2013-11-19
      相关资源
      最近更新 更多