Define a class calledIPAddressComponent
that creates a custom component for inputting four values to form an IP address.
To define the class, create a file calledIPAddressComponent.m
that contains the following class definition with these features:
AValue
public property that stores the IP address.
NumericField
andGridLayout
private properties that place four numeric edit fields in a horizontal row.
Asetup
method that initializesNumericField
andGridLayout
。
Anupdate
method that updates theNumericField
values when the IP address changes.
AhandleNewValue
method that sets theValue
property based on the values of the 4 numeric edit fields.
classdefIPAddressComponent < matlab.ui.componentcontainer.ComponentContainer% IPAddressComponent a set of 4 edit fields for IP Address inputpropertiesValue(4) {mustBeNonnegative亩tBeInteger, mustBeLessThanOrEqual(Value, 255)}= [192 168 1 2];endevents(HasCallbackProperty, NotifyAccess = protected) ValueChanged% ValueChangedFcn callback property will be generatedendproperties(Access = private, Transient, NonCopyable) NumericField(1,4) matlab.ui.control.NumericEditFieldGridLayoutmatlab.ui.container.GridLayoutendmethods(Access=protected)functionsetup(obj)% Set the initial position of this componentobj.Position = [100 100 150 22];% Layoutobj.GridLayout = uigridlayout(obj,[1,5],。..'RowHeight',{22},'ColumnWidth',{30,30,30,30,22},。..'Padding',0,'ColumnSpacing',2);% Building blocksfork = 1:4 obj.NumericField(k) = uieditfield(obj.GridLayout,'numeric',。..'Limits', [0 255],'RoundFractionalValues', true,。..'FontName','Courier New','FontWeight','bold',。..'ValueChangedFcn',@(o,e) obj.handleNewValue());endendfunctionupdate(obj)% Update viewfork = 1:4 obj.NumericField(k).Value = obj.Value(k);endendendmethods(Access=private)functionhandleNewValue(obj) obj.Value = [obj.NumericField.Value];% Execute the event listeners and the ValueChangedFcn callback propertynotify(obj,'ValueChanged');endendend
Next, create the component by calling theIPAddressComponent
constructor method, which is provided by theComponentContainer
class, and return the object ash
。指定一个函数displays the new IP address in the Command Window when the component value changes.
Enter the IP Address192.168.1.10
into the edit fields. MATLAB displays the updated IP address in the Command Window.