Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

Customizing editboxes

September 25, 2013 9 Comments

As a natural follow-up to last week’s article about rich-content log panels (multi-line editbox), today I discuss some additional customizations that can be done to Matlab’s editbox control.

Matlab’s dual editbox controls

There are two distinct uicontrols called ‘editbox’ in Matlab: a single-line editbox and a multi-line editbox. Matlab automatically uses the single-line control if the Max property is set to 1 (the default value, backward compatible with early Matlab versions). If Max > 1, the multi-line editbox is used. Today’s article will focus on features shared by both the single-line and multi-line editbox controls.
Beware of a possible pitfall using Matlab’s editbox controls: when switching styles, including switching between the single-line and multi-line editbox versions, Matlab replaces the underlying Java component with a new component that has default properties. Therefore, if we need any customizations to the uicontrol, then we should ensure that they are done after setting the final uicontrol style, otherwise they will be discarded.

Underlying Java object

As discussed in many prior articles, the first step in customization is to get access to the Matlab control’s underlying Java control. This is done using the findjobj utility:

% Prepare the log editbox
hEditbox = uicontrol('Style','edit', 'String','Matlab', ...);
% Get the underlying Java editbox
jEditbox = findjobj(hLogPanel);
try
    % Multi-line editboxes are contained within a scroll-panel
    jEditbox = handle(jEditbox.getViewport.getView, 'CallbackProperties');
catch
    % probably a single-line editbox
end

% Prepare the log editbox hEditbox = uicontrol('Style','edit', 'String','Matlab', ...); % Get the underlying Java editbox jEditbox = findjobj(hLogPanel); try % Multi-line editboxes are contained within a scroll-panel jEditbox = handle(jEditbox.getViewport.getView, 'CallbackProperties'); catch % probably a single-line editbox end

Borders

As I have explained long ago, all uicontrol borders can be customized using the underlying jEditbox handle’s Border property:

% Create a new border
lineColor = java.awt.Color(1,0,0);  % =red
thickness = 3;  % pixels
roundedCorners = true;
newBorder = javax.swing.border.LineBorder(lineColor,thickness,roundedCorners);
% Override the default control's border
jEditbox.Border = newBorder;  % or: set(jEditbox,'Border',newBorder) or: jEditbox.setBorder(newBorder)
% Remove the border altogether
jEditbox.Border = [];
% Redraw the modified control after we have changed its appearance
jEditbox.repaint;

% Create a new border lineColor = java.awt.Color(1,0,0); % =red thickness = 3; % pixels roundedCorners = true; newBorder = javax.swing.border.LineBorder(lineColor,thickness,roundedCorners); % Override the default control's border jEditbox.Border = newBorder; % or: set(jEditbox,'Border',newBorder) or: jEditbox.setBorder(newBorder) % Remove the border altogether jEditbox.Border = []; % Redraw the modified control after we have changed its appearance jEditbox.repaint;

editbox with regular border
editbox with regular border
   
editbox with custom border
editbox with custom border
   
editbox with no border
editbox with no border


Much more complex and interesting borders can be created in much the same way. Interested readers are referred to the official documentation of Java Borders or any decent Swing textbook.

Text selection

Several jEditbox properties control the text-selection functionality:

  • SelectionStart, SelectionEnd control the characters within the displayed text that are selected (typically with some shaded background color). A value of 0 means the first character, 1 means the second character etc. Setting SelectionStart=0 and SelectionEnd=intmax selects the entire text. We can also use jEditbox.select(selectionStart,selectionEnd). For example:
    set(jEditbox, 'SelectionStart',1, 'SelectionEnd',5);
    jEditbox.select(1,5)  % equivalent alternative

    set(jEditbox, 'SelectionStart',1, 'SelectionEnd',5); jEditbox.select(1,5) % equivalent alternative

    Setting the selected text
    Setting the selected text
  • SelectionColor, SelectedTextColor change the foreground and background colors of the selected text. These properties are overridden whenever the editbox gains focus, so we need to be override them in the editbox’s FocusGainedCallback:
    cbStr = ['set(gcbo,''SelectionColor'',java.awt.Color.red,' ...
                   '''SelectedTextColor'',java.awt.Color.blue)'];
    set(jEditbox, 'FocusGainedCallback', cbStr);

    cbStr = ['set(gcbo,''SelectionColor'',java.awt.Color.red,' ... '''SelectedTextColor'',java.awt.Color.blue)']; set(jEditbox, 'FocusGainedCallback', cbStr);

    Non-standard selection colors and FocusGainedCallback
    Non-standard selection colors, FocusGainedCallback
  • SelectedText is a read-only property holding the text currently selected, between the SelectionStart and SelectionEnd positions. Associated property Text holds the entire text within the editbox. Note that both these properties hold a java.lang.String object, which should be cast to a Matlab string via Matlab’s built-in char function, unless we use Matlab’s get function (which does this conversion for us automatically):
    str = char(jEditbox.getSelectedText);
    str = get(jEditbox,'SelectedText');  % equivalent alternative

    str = char(jEditbox.getSelectedText); str = get(jEditbox,'SelectedText'); % equivalent alternative

Customizing the input caret

The Caret property, which is common to all Java Swing data-entry components, references a javax.swing.text.DefaultCaret object that controls the text caret appearance (this is naturally relevant only for editable editboxes).
The caret object has its own properties that can be customized. For example: BlinkRateRate, Visible and UpdatePolicy. The caret’s StateChangedCallback is invoked whenever the caret position is updated.
Some additional caret-related properties can be set using jEditbox properties: CaretColor and CaretPosition (which uses 0-based, like SelectionStart and SelectionEnd above). Here is an example that modifies the default caret color to something a bit more lively:

% Set the caret color to red
jEditbox.setCaretColor(java.awt.Color(1.0,0,0));
jEditbox.setCaretColor(java.awt.Color.red);	% an alternative

% Set the caret color to red jEditbox.setCaretColor(java.awt.Color(1.0,0,0)); jEditbox.setCaretColor(java.awt.Color.red); % an alternative

Red CaretColor
Red CaretColor

Behavior

Several properties of the jEditbox handle control the editbox behavior beyond what is available by the Matlab uicontrol:

  • Editable – (default=true) a boolean flag indicating whether or not the editbox text can be modified. Note that the Matlab HG handle (hEditbox) only allows setting the Enable property (its jEditbox Java counterpart property is called Enabled), but not to set an enabled yet uneditable control – this can only be done using the Java Editable property.
  • DisabledTextColor controls the text color (default=gray) when the editbox is disabled.
  • DragEnabled – (default=false) a boolean flag indicating whether the editbox contents can be mouse-dragged externally as a DND source (for example, onto an editor, command line or any DND target). The DropMode, DropLocation, DropTarget and TransferHandler properties enable the editbox act as a DND target, accepting externally-dragged data as input sources.
  • FocusAccelerator – (default=char(0)) sets the keyboard accelerator sequence that will cause the receiving text component to get the focus. The accelerator will be the key combination of the <Alt> key and the specified character, converted to upper-case. Any previous key accelerator setting, including menu-bar accelerators, will be superseded. A char(0) key has the effect of turning off the focus accelerator. By default, there is no focus accelerator key (i.e., an accelerator of \0=char(0)). For example, let us set the accelerator to <Alt>-E, overriding the menu-bar’s default accelerator for the Edit menu:
    >> jEditbox.setFocusAccelerator('e');
    >> jEditbox.getFocusAccelerator		% let us check...
    ans =
    E	% 'e' converted to 'E', meaning an Alt-E accelerator

    >> jEditbox.setFocusAccelerator('e'); >> jEditbox.getFocusAccelerator % let us check... ans = E % 'e' converted to 'E', meaning an Alt-E accelerator

Additional editbox behavior can be customized using the dozens of callback functions that jEditbox exposes. These callbacks enable modifying the appearance and behavior of the editbox based on events such as mouse movements (into/over/out-of), focus gain/loss, key-clicks (that enable input data validation) etc. I plan to describe a data input-validation function based on these callbacks, using some of the customizations shown above, in next week’s article.

Available report – “Advanced Customizations of Matlab Uicontrols”

Interested readers can find more information about these and other possible customizations in my report on “Advanced Customizations of Matlab Uicontrols“. This 90-page PDF report can be purchased here ($29, please allow 24 hours for delivery by email). The report explains how to customize Matlab’s uicontrols in ways that are simply not possible using documented Matlab properties. This includes treatment of push buttons, toggle buttons, radio buttons, checkboxes, editboxes, listboxes, popup menus (aka combo-boxes/drop-downs), sliders, labels, and tooltips. Much of the information in the report is also available in hard-copy format in chapter 6 of my Matlab-Java programming book.

Related posts:

  1. Customizing menu items part 2 – Matlab menu items can be customized in a variety of useful ways using their underlying Java object. ...
  2. Customizing Matlab labels – Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...
  3. Setting line position in an edit-box uicontrol – Matlab uicontrols have many useful features that are only available via Java. Here's how to access them....
  4. Customizing listbox & editbox scrollbars – Matlab listbox and multi-line editbox uicontrols have pre-configured scrollbars. This article shows how they can be customized....
  5. Customizing combobox popups – Matlab combobox (dropdown) popups can be customized in a variety of ways. ...
  6. Customizing listbox/combobox items – Matlab listboxes can be customized using custom Java cell-renderers. ...
Callbacks FindJObj GUI Internal component Java uicontrol
Print Print
« Previous
Next »
9 Responses
  1. Editable combo-box | Undocumented Matlab October 9, 2013 at 08:41 Reply

    […] underlying Java control, thereby improving its appearance and functionality. My two previous articles on the Matlab editbox were a classic example of this mechanism. Unfortunately, this technique does […]

  2. Raj March 7, 2014 at 08:23 Reply

    Hey Yair,
    I’ve got a question. Your Text Selection Method works fine! I’ve tried make a search function for my editbox so it can mark(select) every word he found. But the Selection does work only once. Is there no way of multiple selections?
    Greetings

    • Yair Altman March 10, 2014 at 10:13 Reply

      @Raj – I do not think that this is supported in a single-line editbox, but you can always use a multi-line editbox or listbox.

      • Raj March 12, 2014 at 01:39

        Hi,
        of course i meant multiline editbox 🙂 I figured it out myself with the addHighlight method of jEditbox 🙂
        Thanks anyway

  3. Nipurn Jain March 13, 2018 at 08:57 Reply

    How to determine cursor position in ‘edit’ uicontrol?

    I have an application where there are several buttons that apply a specific function to the data. The user can also enter values in the edit box. However if the cursor is positioned in the edit box and a button is pressed the new function will appear at the end of the edit box and I need that this appear at cursor position how to do this?
    Is it possible by using javaframe available on matlab?

    • Yair Altman March 13, 2018 at 10:45 Reply

      @Nipurn – yes this is possible using findjobj:

      hEditbox = uicontrol('style','edit', ...); drawnow
      jEditbox = findjobj(hEditbox);
      try jEditbox = jEditbox.getViewport.getView; end  % in case it's a multi-line editbox
      caretPos = jEditbox.getCaretPosition;  % or: =get(jEditbox,'CaretPosition');

      hEditbox = uicontrol('style','edit', ...); drawnow jEditbox = findjobj(hEditbox); try jEditbox = jEditbox.getViewport.getView; end % in case it's a multi-line editbox caretPos = jEditbox.getCaretPosition; % or: =get(jEditbox,'CaretPosition');

      There’s also a corresponding setCaretPosition(position) method.
      See related: http://undocumentedmatlab.com/blog/setting-line-position-in-edit-box-uicontrol

  4. David May 8, 2018 at 18:08 Reply

    Is there anyway to get this to work with app designer? I can’t seem to find any java objects in app designer and I am not sure if there is a way that I just don’t know about.

    • Yair Altman May 8, 2018 at 18:36 Reply

      @David – almost all the GUI customizations described in this blog relate only to the legacy (Java-based) figures. AppDesigner-created figures (so-called “uifigures”) are web-based HTML pages displayed in a browser window, which is an entirely different technology. To customize uifigure controls see the series of posts on uifigure customization: http://undocumentedmatlab.com/blog/tag/uifigure

    • David May 8, 2018 at 18:42 Reply

      Hi Yair,

      Thanks for the quick reply. I will take a look!

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitable (6) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
Contact us
Captcha image for Custom Contact Forms plugin. You must type the numbers shown in the image
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top