Search code examples
matlabformattingalignmentuicontrol

Aligning text and edit uicontrols


I am creating GUI and I want to have inputs and results there.

I have text fields as labels and edit or popup for inputs. When I have

uicontrol('style','text','string','foo','units','centimeters','position',[1 1 1 0.5]);
uicontrol('style','edit','string','foo','units','centimeters','position',[2 1 1 0.5]);

I get the foo strings slightly misaligned, baseline of the text field is slightly above the baseline of edit/pop field.

How can I align those fields?


Solution

  • Unfortunately this requires accessing the underlying Java. The method is similar to Amro's approach here for a pushbutton and utilizes the external findjobj function:

    h.t = uicontrol('style','text','string','foo','units','centimeters','position',[1 1 1 0.5]);
    h.e = uicontrol('style','edit','string','foo','units','centimeters','position',[2 1 1 0.5]);
    jh = findjobj(h.t);
    jh.setVerticalAlignment(javax.swing.JLabel.CENTER)
    

    Unfortunately, this is still off by a pixel or two:

    yay

    I'd say just bump the text box by pixel, as necessary:

    oldunits = get(h.t, 'Units');
    set(h.t, 'Units', 'Pixels');
    pos = get(h.t, 'Position');
    
    pos(2) = pos(2) + 1;
    
    set(h.t, 'Position', pos)
    set(h.t, 'Units', oldunits)
    

    Which gives us:

    yay2


    Edit: Modifying the BackgroundColor property of the edit box has no effect (though setting it to none makes it a black box...), and the box will remain the default color. Per The MathWorks, this is a design decision:

    This is a expected behavior in the way that MATLAB displays the BackgroundColor for editable text objects.

    This could also most likely be updated by leveraging the underlying Java, but I'm not familiar.