Controls


You can obtain a control directly from a dialog by calling the getControl() method. You can obtain a control's model by calling the getModel() method on the control, or by calling getByName() on the model of the object in which it is contained. In other words, you can get a control's model from the dialog's model. The code in Listing 5 demonstrates the options available.

Listing 5: Get the button or the button's model.
start example
 oHelloDlg.getControl("OKButton")               'Get the UnoControlButton oHelloDlg.getControl("OKButton").getModel()    'Get the UnoControlButtonModel oHelloDlg.getModel().getByName("OKButton")     'Get the UnoControlButtonModel 
end example
 
Tip  

You can insert controls into dialogs and forms, but not all controls work in dialogs. Some controls require a data source, but as of OOo 1.1.1, a dialog is not able to contain a data source. This chapter deals only with controls that can be inserted into a dialog.

The control types that can be inserted into a dialog are defined in the com.sun.star.awt module (see Table 11 and Figure 6). Notice the similarity between the service name of the control and the service name of the control's model.

Table 11: Controls and their models defined in the com.sun.star.awt module.

Control

Model

Description

UnoControlButton

UnoControlButtonModel

Button

UnoControlCheckBox

UnoControlCheckBoxModel

Check box

UnoControlComboBox

UnoControlComboBoxModel

Combo box

UnoControlCurrencyField

UnoControlCurrencyFieldModel

Currency field

UnoControlDateField

UnoControlDateFieldModel

Date field

UnoControlDialog

UnoControlDialogModel

Dialog

UnoControlEdit

UnoControlEditModel

Text edit field

UnoControlFileControl

UnoControlFileControlModel

Select a file

UnoControlFixedLine

UnoControlFixedLineModel

Fixed line

UnoControlFixedText

UnoControlFixedTextModel

Display fixed

UnoControlFormattedField

UnoControlFormattedFieldModel

Formatted field

UnoControlGroupBox

UnoControlGroupBoxModel

Group box

UnoControlImageControl

UnoControlImageControlModel

Display an image

UnoControlListBox

UnoControlListBoxModel

List box

UnoControlNumericField

UnoControlNumericFieldModel

Numeric field

UnoControlPatternField

UnoControlPatternFieldModel

Pattern field

UnoControlProgressBar

UnoControlProgressBarModel

Progress bar

UnoControlRadioButton

UnoControlRadioButtonModel

Radio button

UnoControlScrollBar

UnoControlScrollBarModel

Scroll bar

UnoControlTimeField

UnoControlTimeFieldModel

Time field

Note  

To assist in the demonstration of the different dialog controls, create a dialog called OOMESample. As the control types are discussed, I will direct you to add controls to the OOMESample dialog. See Figure 7 for the final dialog. Start by creating the OOMESample dialog and making it large enough to fill most of the screen.

click to expand
Figure 7: OOMESample dialog referred to throughout this chapter.

Control Button

A control button is a standard button that causes something to happen when it is "pressed." A button's type is controlled by the PushButtonType property in a button's model. A button can be set to automatically close or cancel a dialog without writing an event handler; a default event handler is provided automatically for these predefined actions (see Table 12 ).

Table 12: Values defined by the com.sun.star.awt.PushButtonType enumeration.

Enumeration

Description

STANDARD

The default value. You must write your own event handler.

OK

Act like an OK button by closing the dialog and returning 1 from the execute() function.

CANCEL

Act like a Cancel button by closing the dialog and returning 0 from the execute() function.

HELP

Act like a Help button and open the help URL.

A control button can display a text label set by the Label property or a graphic image set by the ImageURL property. If the button displays an image rather than a label, the image is aligned based on a value defined by the ImageAlign constant group (see Table 13 ).

Table 13: Constants defined by the com.sun.star.awt.ImageAlign constant group.

Constant

Name

Description

LEFT

Align the image to the left.

1

TOP

Align the image to the top.

2

RIGHT

Align the image to the right.

3

BOTTOM

Align the image to the bottom.

Tip  

Although a button can contain an image, it crops the image to fit. Use an Image control, rather than a button, if you need to scale the image.

The button model supports many of the same properties as the dialog model but it also supports some button-specific properties (see Table 14 ).

Table 14: Properties defined by the com.sun.star.awt.UnoControlButtonModel service.

Property

Description

DefaultButton

If True, this button is the default button.

ImageAlign

Specify how an image is aligned in the button (see Table 13).

ImageURL

URL of the image to display on the button. If the image is too large, it is cropped.

Label

String label displayed on the control.

Printable

If True, the button is printed when the document is printed.

PushButtonType

The default button action (see Table 12).

State

If 1, the button is activated; otherwise , the state is 0.

Tabstop

If True, the control can be reached by using the Tab key.

BackgroundColor

Dialog's background color as a Long Integer.

Enabled

If True, the dialog is enabled.

FontDescriptor

FontDescriptor structure for the text in the dialog's caption bar.

FontEmphasisMark

FontEmphasis for the text in the dialog's caption bar.

FontRelief

FontRelief for the text in the dialog's caption bar.

HelpText

Dialog's help text as a String.

HelpURL

Dialog's help URL as a String.

TextColor

Dialog's text color as a Long Integer.

TextLineColor

Dialog's text line color as a Long Integer.

Add an OK button to close the OOMESample dialog. Add a second button, named ClickButton, that calls Listing 6.

Listing 6: RunOOMEDlg and OOMEDlgButton are in the DlgCode module in this chapter's source code files as SC17.sxw.
Note  
start example
 Option Explicit REM Global variables Dim oOOMEDlg     'The run-time dialog that is created Dim nClickCount% 'Number of times the button was clicked Sub RunOOMEDlg   REM Declare the primary variables   Dim oLib        'Library that contains the dialog   Dim oLibDlg     'Dialog as stored in the library   REM Load the library and the dialog   DialogLibraries.loadLibrary("OOMECH17")   oLib = DialogLibraries.getByName("OOMECH17")   oLibDlg = oLib.getByName("OOMESample")   oOOMEDlg = CreateUnoDialog(oLibDlg)   REM Initial setup code here   nClickCount = 0   oOOMEDlg.getModel.Title = "OpenOffice.org Macros Explained Sample Dialog"   REM This can be used with the check box to be added.   REM oOOMEDlg.getModel().getByName("CheckBox").TriState = True   REM Run the dialog   oOOMEDlg.execute() End Sub Sub OOMEDlgButton   Dim oButtonModel   nClickCount = nClickCount + 1   oButtonModel = oOOMEDlg.getModel().getByName("ClickButton")   oButtonModel.Label = "Click " & nClickCount End Sub 
end example
 

Add two buttons to the OOMESample dialog. Set one button to close the dialog when it is selected; label the button "Close" and set the button type to OK. The close button will automatically close the dialog when it is selected. Name the second button ClickButton and set the label to "Click Here". Enter the code in Listing 6 and set the "When initiating" event of the ClickButton to call the OOMEDlgButton subroutine. When the ClickButton is selected, its label is changed to indicate the number of times that the button has been clicked.

Check Box

Although a check box is usually used to indicate a single state of yes or no, the check box in OOo can be used as a tristate check box. The default behavior is for a check box to support the states 0 (not checked) and 1 (checked); this is the State property in the model. If the TriState property is True, however, a third state of 2 is allowed. The third state is displayed as checked, but the check box is dimmed. The properties in Table 15 are supported by the check box button model.

Table 15: Properties defined by com.sun.star.awt.UnoControlCheckBoxModel.

Property

Description

Label

String label displayed on the control.

Printable

If True, the button is printed when the document is printed.

State

If 0, the button is not checked; if 1, the button is checked; 2 is the "don't know" state.

Tabstop

If True, the control can be reached by using the Tab key.

TriState

If True, the button supports the "don't know" state of 2.

Enabled

If True, the dialog is enabled.

FontDescriptor

FontDescriptor structure for the text in the dialog's caption bar.

FontEmphasisMark

FontEmphasis for the text in the dialog's caption bar.

FontRelief

FontRelief for the text in the dialog's caption bar.

HelpText

Dialog's help text as a String.

HelpURL

Dialog's help URL as a String.

TextColor

Dialog's text color as a Long Integer.

TextLineColor

Dialog's text line color as a Long Integer.

Add a check box to the OOMESample dialog and name it CheckBox. The "When initiating" event will call the code in Listing 7.

Listing 7: OOMEDIgCheckBox is in the DlgCode module in this chapter's source code files as SC17.sxw.
Note  
start example
 Sub OOMEDlgCheckBox   Dim oModel   oModel = oOOMEDlg.getModel().getByName("CheckBox")   oModel.Label = "State " & oModel.state End Sub 
end example
 

Add a check box to the sample dialog and set the button name to CheckBox. In the RunOOMEDlg routine, add code to the initialization section to set the check box to be a tristate check box. The TriState property can also be enabled in the Properties dialog for the control in the Basic IDE.

 oOOMEDlg.getModel().getByName("CheckBox").TriState = True 

Add the code in Listing 7 and then set the "When initiating" event to call the routine in Listing 7. When the check box is selected, its label is updated to show its state.

Radio Button

Radio buttons are usually used to select one item from a small list. (For a large list, it's common to use a combo box or a list box.) Radio buttons are always used in a group, and only one radio button in each group is active at a time. When a radio button is selected, OOo automatically marks all other radio buttons in the same group as not active.

Every control supports the UnoControlDialogElement service (see Table 10). The TabIndex property specifies the order in which controls are visited while repeatedly pressing the Tab key. The TabIndex property is usually set in the IDE at design time by setting the control's "order" property. Unfortunately , a different name is used in the IDE than in the defining service.

In OOo, a visual grouping that uses an UnoControlGroupBox has no effect other than to draw a frame around the controls. In other words, it provides a visual reminder that the radio buttons should be grouped, but it does not group them. Radio buttons are in the same group if (and only if) they have a sequential tab order; for example, in Visual Basic, radio buttons are grouped based on the group box. Create all of the radio buttons that will exist in a single group in sequence. By creating the buttons sequentially, they will automatically have sequential tab stops and will therefore all be in the same group. If you then create a group box to place around the radio buttons, the group box will break the tab-stop sequence so that you can safely create a new sequence of radio buttons. See Table 16 .

Table 16: Properties in the com.sun.star.awt.UnoControlRadioButtonModel.

Property

Description

Label

String label displayed on the control.

Printable

If True, the button is printed when the document is printed.

State

If 0, the button is not checked; if 1, the button is checked.

Tabstop

If True, the control can be reached by using the Tab key.

Enabled

If True, the dialog is enabled.

FontDescriptor

FontDescriptor structure for the text in the dialog's caption bar.

FontEmphasisMark

FontEmphasis for the text in the dialog's caption bar.

FontRelief

FontRelief for the text in the dialog's caption bar.

HelpText

Dialog's help text as a String.

HelpURL

Dialog's help URL as a String.

TextColor

Dialog's text color as a Long Integer.

TextLineColor

Dialog's text line color as a Long Integer.

Note  

Add three radio buttons to the OOMESample dialog.

Add three radio buttons to the sample dialog and name them OBSet, OBClear, and OBUnknown. The three radio buttons will influence the state of the check box, so set an appropriate label as well (see Figure 7). In other words, the OB Set button will set the check box, the OBClear radio button will clear the check box, and the OBUnknown radio button will set the check box to the "don't know" state of 3. Enter the macro in Listing 8 and then set the "When initiating" event to call the OOMEDlgRadioButton routine for each of the three radio buttons. Each of the radio buttons is inspected to see which one is currently selected.

Listing 8: OOMEDlgRadioButton is in the DlgCode module in this chapter's source code files as SC17.sxw.
start example
 REM When a radio button is selected, set the state of the check box REM based on which radio button is selected. Set the check box REM label to indicate why the check box was set to that state. Sub OOMEDlgRadioButton   Dim oModel   Dim i As Integer   Dim sBNames (0 To 2) As String   REM These are ordered so that the button names are in the order   REM that will set the check box state.   sBNames(0) = "OBClear" : sBNames(1) = "OBSet" : sBNames(2) = "OBUnknown"   For i = 0 To 2     oModel = oOOMEDlg.getModel().getByName(sbNames(i))     If oModel.State = 1 Then       oOOMEDlg.getModel().getByName("CheckBox").State = i       oOOMEDlg.getModel().getByName("CheckBox").Label = "Set by " & sBNames(i)       REM oOOMEDlg.getModel().getByName("RBFrame").Label = sBNames(i)       Exit For     End If   Next End Sub 
end example
 

Group Box

The purpose of a group box is to draw a visual frame-a useful visual cue to the user that a group of controls are related in some way. The group box model supports the properties Enabled, FontDescriptor, FontEmphasisMark, FontRelief, HelpText, HelpURL, TextColor, TextLineColor, Label, and Printable.

Note  

Draw a group box around the three radio buttons in the OOMESample dialog.

Draw a group box around the three radio buttons and name the group box RBFrame. The macro in Listing 8 contains one line of code that will set the frame label to the name of the currently selected radio button. Remove the comment mark (REM) from the front of this line or the frame label will not update.

Fixed Line Control

The fixed line control, like the group box control, provides a nice visual separator for the user. Its only purpose is to draw a separating line in the dialog. The only interesting property in the fixed-line-control model is the Orientation property, which specifies if the line is drawn horizontally (0) or vertically (1).

Combo Box

A combo box, sometimes called a "drop-down" control, is an input field with an attached list box. The combo box control is used to select a single value. The attached list box facilitates selecting a value from a predefined list. The selected text is available from the Text property in the control's model. See Table 17 .

Table 17: Properties defined by com.sun.star.awt.UnoControlComboBoxModel.

Property

Description

Autocomplete

If True, automatic completion of text is enabled.

Border

Specify no border (0), a 3-D border (1), or a simple border (2) as an Integer.

Dropdown

If True, the control contains a drop-down button.

LineCount

Maximum line count displayed in the drop-down box.

MaxTextLen

Maximum character count. If 0, the text length is unlimited.

Printable

If True, the button is printed when the document is printed.

ReadOnly

If True, the Text entry cannot be modified by the user.

StringItemList

Array of strings that identify the items in the list.

Tabstop

If True, the control can be reached by using the Tab key.

Text

Text that is displayed in the input field section of the box.

BackgroundColor

Dialog's background color as a Long Integer.

Enabled

If True, the dialog is enabled.

FontDescriptor

FontDescriptor structure for the text in the dialog's caption bar.

FontEmphasisMark

FontEmphasis for the text in the dialog's caption bar.

FontRelief

FontRelief for the text in the dialog's caption bar.

HelpText

Dialog's help text as a String.

HelpURL

Dialog's help URL as a String.

TextColor

Dialog's text color as a Long Integer.

TextLineColor

Dialog's text line color as a Long Integer.

Although it is considered good practice to interact with a control through the control's model, the combo box control contains some useful utility methods that are not directly available from the model. The methods listed in Table 18 essentially provide a shortcut to writing your own array utility functions to add and remove items from the StringItemList array in Table 17.

Table 18: Extra utility methods supported by the combo box control.

Method

Description

addItem(String, position)

Add an item at the specified position.

addItems(StringArray, position)

Add multiple items at the specified position.

removeItems(position, count)

Remove a number of items at the specified position.

Note  

Add a combo box to the OOMESample dialog and name it ColorBox.

Add a combo box to the dialog with a name of "ColorBox". Select the "List entries" property and enter the three values "Red", "Green", and "Blue". To place each entry on a separate line, type the word Red and press Ctrl-Enter, type the word Green and press Ctrl-Enter, and so on-it took me longer than it should have to figure out how to do this. It's easy, of course, to simply set these values directly into the model by setting the StringItemList property shown in Table 17.

Enter the code shown in Listing 9 and then set the "Text modified" event to call the OOMDDlgColorBox subroutine in Listing 9. The "Text modified" event causes the subroutine to be called every time that the text in the input line changes. In other words, while typing text, the subroutine is called with every keystroke. If the "Item status changed" event is used, then the subroutine is called when a new selection is chosen from the drop-down list.

Listing 9: OOMEDIgColorBox is in the DlgCode module in this chapter's source code files as SC17.sxw.
start example
 Sub OOMEDlgColorBox   Dim oModel   Dim s As String   oModel = oOOMEDlg.getModel().getByName("ColorBox")   s = oModel.Text   If s = "Red" Then     REM Set to Red     oModel.BackGroundColor = RGB(255, 100, 0)   ElseIf s = "Green" Then     REM Set to Green     oModel.BackGroundColor = RGB(0, 255, 0)   ElseIf s = "Blue" Then     REM Set to Blue     oModel.BackGroundColor = RGB(0, 0, 255)   Else     Rem set back to white     oModel.BackGroundColor = RGB(255, 255, 255)   End If End Sub 
end example
 

The macro in Listing 9 changes the background color of the drop-down list box based on the value of the entered text. The text comparison is case sensitive, so the text in the drop-down box must match exactly.

Text Edit Controls

The UnoControlEdit service is a basic edit field that acts as the base service for the other edit fields. An edit control is used to hold regular text. It is possible to limit the length of the text and to even add scroll bars. The edit control model supports the properties shown in Table 19 .

Table 19: Properties defined by the com.sun.star.awt.UnoControlEditModel service.

Property

Description

Align

Specify that the text is aligned left (0), center (1), or right (2).

Border

Specify no border (0), a 3-D border (1), or a simple border (2).

EchoChar

A password field displays the character specified by this integer rather than the entered text.

HScroll

If True, the text in the control can be scrolled in the horizontal direction.

HardLineBreaks

If True, hard line breaks are returned by the control's getText() method.

MaxTextLen

Maximum number of characters the control may contain. If zero, the text length is not purposely limited.

MultiLine

If True, the text may use more than one line.

Printable

If True, the control is printed with the document.

ReadOnly

If True, the control's content cannot be modified by the user.

Tabstop

If True, the control can be reached by using the Tab key.

Text

The text that is displayed in the control.

VScroll

If True, the text in the control can be scrolled in the vertical direction.

BackgroundColor

Dialog's background color as a Long Integer.

Enabled

If True, the dialog is enabled.

FontDescriptor

FontDescriptor structure for the text in the dialog's caption bar.

FontEmphasisMark

FontEmphasis for the text in the dialog's caption bar.

FontRelief

FontRelief for the text in the dialog's caption bar.

HelpText

Dialog's help text as a String.

HelpURL

Dialog's help URL as a String.

TextColor

Dialog's text color as a Long Integer.

TextLineColor

Dialog's text line color as a Long Integer.

Although I encourage you to use the model for most things, some features are not available without going directly to the control. For example, the control supplies the capability of selecting some or all of the text and determining which portion of the text is currently selected. In a regular document, the current controller provides this capability, but controls in dialogs combine the controller's capabilities with the control itself. To obtain or set the selected range, use the Selection structure (see Table 20 ).

Table 20: Properties in the com.sun.star.awt.Selection structure.

Property

Description

Min

Lower limit of the range as a Long Integer.

Max

Upper limit of the range as a Long Integer.

The control uses the Selection structure to get and set the current text selection range. The control is also able to directly return the text that is selected in a text control. The purpose is to allow a user to select only a portion of the text and to determine which portion is selected. Table 21 contains the standard text methods supported by text type controls.

Table 21: Methods defined by the com.sun.star.awt.XTextComponent interface.

Method

Description

addTextListener(XTextListener)

Add a text listener.

removeTextListener(XTextListener)

Remove a text listener.

setText(string)

Set the model's Text property (see Table 19).

insertText(Selection, string)

Insert the string at the specified Selection location.

getText()

Get the model's Text property (see Table 19).

getSelectedText()

Return the currently selected text string.

setSelection(Selection)

Set the text that is selected (see Table 18).

getSelection()

Return a Selection object that identifies the selected text (see Table 18).

isEditable()

Return the model's ReadOnly flag (see Table 19).

setEditable(boolean)

Set the model's ReadOnly flag (see Table 19).

setMaxTextLen(len)

Set the model's MaxTextLen property (see Table 19).

getMaxTextLen()

Get the model's MaxTextLen property (see Table 19).

Currency Control

The currency control is used to input and edit monetary values. The currency control is defined by the UnoControlCurrencyField service, which also implements the standard edit control service. Table 22 lists some properties that are unique to the currency model, all of which may also be set from the control's property dialog in the IDE. Pay special attention to the default values, and notice that the property dialog uses Yes and No rather than True and False. Besides the specific properties in Table 22, the currency control model also supports these properties: BackgroundColor, Border, Enabled, FontDescriptor, FontEmphasisMark, FontRelief, HelpText, HelpURL, Printable, ReadOnly, Tabstop, TextColor, and TextLineColor.

Table 22: Properties in the com.sun.star.awt.UnoControlCurrencyFieldModel service.

Property

Description

Default

CurrencySymbol

Currency symbol as a String.

$

DecimalAccuracy

Decimal accuracy as an Integer.

2

PrependCurrencySymbol

If True, the currency symbol is prepended to the currency amount.

No

ShowThousandsSeparator

If True, the thousands separator is displayed.

No

Spin

If True, the control has a spin button.

No

StrictFormat

If True, the entered text is checked during the user input.

No

Value

The value displayed in the control as a floating-point Double.

ValueMax

The maximum value as a floating-point Double.

1000000

ValueMin

The minimum value as a floating-point Double.

-1000000.00

ValueStep

The amount that the spin button changes the entered values as a Double.

1

Tip  

The default values shown in Table 22 are for the United States. Local specific default values are used.

The XCurrencyField interface implemented by the currency control defines methods to get and set the properties defined in Table 22. The XSpinField interface, which is also supported by the currency control, defines methods to interact with the spin control (see Table 23 ).

Table 23: Methods defined by the the com.sun.star.awt.XSpinField interface.

Method

Description

addSpinListener(XSpinListener)

Add a spin listener.

removeSpinListener(XSpinListener)

Remove a spin listener.

up()

Increases the value by ValueStep (see Table 22).

down()

Decreases the value by ValueStep (see Table 22).

first()

Set the value to ValueMin (see Table 22).

last()

Set the value to ValueMax (see Table 22).

enableRepeat(boolean)

Enable/disable automatic repeat mode.

Tip  

All of the edit controls that support spin buttons also support the methods in Table 23.

Numeric Control

The numeric control is used to accept numeric input. The numeric control is almost identical to the currency control except that the numeric control does not support the properties CurrencySymbol or PrependCurrencySymbol-even the default values are the same. If you know how to use a currency control, you know how to use a numeric control.

Date Control

The date control is a text-edit control that supports date input. The input formats supported by the date control are predefined and set based on a numeric constant (see Table 24 ). The descriptions show formats such as (DD/MM/YY), but in reality, the separator is locale specific. In other words, dates are shown and edited in a way that is appropriate for where you live. The last two formats are not locale specific because they are described by the DIN 5008 standard.

Table 24: Date input formats supported by a Date control.

Value

Descriptiona

Default system short format.

1

Default system short format with a two-digit year (YY).

2

Default system short format with a four-digit year (YYYY).

3

Default system long format.

4

Short format (DD/MM/YY).

5

Short format (MM/DD/YY).

6

Short format (YY/MM/DD).

7

Short format (DD/MM/YYYY).

8

Short format (MM/DD/YYYY).

9

Short format (YYYY/MM/DD).

10

Short format for DIN 5008 (YY-MM-DD).

11

Short format for DIN 5008 (YYYY-MM-DD).

The date control (see Table 25 ) is similar to the currency control in that it supports a minimum value, a maximum value, and a spin control. The spin control works by incrementing or decrementing the portion of the date in which it resides. For example, if the cursor is in the month field, the spin control affects the month rather than the year or the day.

Table 25: Properties in the com.sun.star.awt.UnoControlDateFieldModel service.

Property

Definition

Date

The date as a Long Integer.

DateFormat

Date format as an Integer (see Table 24).

DateMax

Maximum allowed date as a Long Integer.

DateMin

Minimum allowed date as a Long Integer.

DropDown

If True, a drop-down exists that shows a calendar for choosing a date.

Spin

If True, spin buttons are drawn.

StrictFormat

If True, the date is checked during the user input.

BackgroundColor

Dialog's background color as a Long Integer.

Border

Specify no border (0), a 3-D border (1), or a simple border (2).

Enabled

If True, the dialog is enabled.

FontDescriptor

FontDescriptor structure for the text in the dialog's caption bar.

FontEmphasisMark

FontEmphasis for the text in the dialog's caption bar.

FontRelief

FontRelief for the text in the dialog's caption bar.

HelpText

Dialog's help text as a String.

HelpURL

Dialog's help URL as a String.

TextColor

Dialog's text color as a Long Integer.

TextLineColor

Dialog's text line color as a Long Integer.

Tip  

The DropDown property allows for a drop-down calendar that greatly facilitates date entry. The drop-down capability may not function in versions of OpenOffice.org prior to 1.1.1.

Note  

Add a date input control to the OOMESample dialog and name it MyDateField.

The Date data type used by Basic is not compatible with the Date property used in a date control. The date control uses a Long that represents the date in the form YYYYMMDD. For example, "February 3, 2004" is represented as the long integer 20040203. The Basic function CDateTolso() converts a Basic Date variable to the required format. Add a date input control and name it MyDateField. The code in Listing 10 sets the date control to the current day.

Listing 10: Initialize a date control to today's date.
start example
 REM Set the initial date to TODAY   oOOMEDlg.getModel().getByName("MyDateField").Date = CdateToIso(Date()) 
end example
 

Although the control implements methods that get and set properties in the model, the more interesting methods are related to the user interface. While using a date field, press the Page Up key to cause the control to jump to the "last" date. By default, the last date is the same as the DateMax property. The last date is set by the control and not by the model, and it may differ from the DateMax. Analogously, the pressing the Page Down key causes the control to jump to the "first" date. The first and last dates are set using the setFirst() and setLast() methods shown in Table 26 . Use the method isEmpty() to determine if the control contains no value, and use the method setEmpty() to cause the control to contain no value.

Table 26: Methods in the com.sun.star.awt.UnoControlDateField interface.

Method

Description

setDate(long)

Set the model's Date property.

getDate()

Get the model's Date property.

setMin(long)

Set the model's DateMin property.

getMin(long)

Get the model's DateMin property.

setMax(long)

Set the model's DateMax property.

getMax(long)

Get the model's DateMax property.

setFirst(long)

Set the date used for the Page Down key.

getFirst()

Get the date used for the Page Down key.

setLast(long)

Set the date used for the Page Up key.

getLast()

Get the date used for the Page Up key.

setLongFormat(boolean)

Set to use the long date format.

isLongFormat()

Return True if the long date format is used.

setEmpty()

Set the empty value.

isEmpty()

Return True if the current value is empty.

setStrictFormat(boolean)

Set the model's StrictFormat property.

isStrictFormat()

Get the model's StrictFormat property.

Time Control

The time control is very similar to the date control. Time values may indicate either a time on a clock or a length of time (duration). The supported formats are shown in Table 27 .

Table 27: Time input formats supported by a time control.

Value

Description

Short 24- hour format.

1

Long 24-hour format.

2

Short 12-hour format.

3

Long 12-hour format.

4

Short time duration.

5

Long time duration.

The properties supported by the time-control model are shown in Table 28 . Modify Table 25 by changing the word Date to Time, and by removing the DropDown property, and Table 25 becomes Table 28. In other words, the date and time models are almost identical.

Table 28: Properties in the com.sun.star.awt.UnoControlTimeFieldModel service.

Property

Definition

Time

The time as a Long Integer.

TimeFormat

Time format as an Integer (see Table 27).

TimeMax

Maximum allowed date as a Long Integer.

TimeMin

Minimum allowed date as a Long Integer.

Spin

If True, spin buttons are drawn.

StrictFormat

If True, the date is checked during the user input.

As expected, the methods supported by the date control are similar to the methods supported by the time control (see Table 26). There are two differences: The time control has getTime() and setTime() rather than getDate() and setDate(), and the time control does not support the methods setLongFormat() and isLongFormat().

The time control uses a Long Integer to store and return the entered value. The rightmost two digits represent fractions of a second, the next two digits represent seconds, the next two digits represent minutes, and the leftmost two digits represent hours. Leading digits are, of course, not returned because the value is really a Long Integer. The good news, however, is that the values are easy to extract. Assuming that the dialog contains a time field named MyTimeField, the code in Listing 11 obtains the time value and extracts the hours, minutes, seconds, and portions of a second.

Listing 11: Extracting values from a time control.
start example
 n = oOOMEDlg.getModel().getByName("MyTimeField").Time   h = n / 1000000         REM Get the hours   m = n / 10000 MOD 100   REM Get the minutes   s = n / 100 MOD 100     REM Get the seconds   ss = n MOD 100          REM portions of a second 
end example
 

Formatted Control

The formatted control is a generic number input field. Numbers can be entered as a formatted number, percent, currency, date, time, scientific, fraction, or Boolean number. Unfortunately, this level of control comes with a price. The formatted control requires a numeric formatter provided by OpenOffice.org to function. The easiest method to associate a formatted control to a numeric format object is to use the Properties dialog in the IDE. To use a number formatter, the following sequence of events is likely to occur:

  1. Choose a numeric format.

  2. Use the methods in Table 31 to search the FormatsSupplier (see Table 29 ) using the constants in Table 30 to find or create a suitable number formatter.

    Table 29: Properties in the com.sun.star.awt.UnoControlFormattedFieldModel service.

    Property

    Description

    TreatAsNumber

    If True, the text is treated as a number. This property controls how the other values are treated.

    EffectiveDefault

    The default value of the formatted field. This is a number or a string based on TreatAsNumber.

    EffectiveMax

    The maximum value as a Double if TreatAsNumber is True.

    EffectiveMin

    The minimum value as a Double if TreatAsNumber is True.

    EffectiveValue

    The current value as a Double or a String based on the value of TreatAsNumber.

    FormatKey

    Long Integer that specifies the format for formatting.

    FormatsSupplier

    XNumberFormatsSupplier that supplies the formats used by this control.

    Spin

    If True, a spin control is used.

    StrictFormat

    If True, the text is checked during the user input.

    Align

    Specify that the text is aligned left (0), center (1), or right (2).

    Border

    Specify no border (0), a 3-D border (1), or a simple border (2).

    MaxTextLen

    Maximum number of characters the control may contain. If zero, the text length is not purposely limited.

    Printable

    If True, the control is printed with the document.

    ReadOnly

    If True, the control's content cannot be modified by the user.

    Tabstop

    If True, the control can be reached by using the Tab key.

    Text

    The text that is displayed in the control.

    BackgroundColor

    Dialog's background color as a Long Integer.

    Enabled

    If True, the dialog is enabled.

    FontDescriptor

    FontDescriptor structure for the text in the dialog's caption bar.

    FontEmphasisMark

    FontEmphasis for the text in the dialog's caption bar.

    FontRelief

    FontRelief for the text in the dialog's caption bar.

    HelpText

    Dialog's help text as a String.

    HelpURL

    Dialog's help URL as a String.

    TextColor

    Dialog's text color as a Long Integer.

    TextLineColor

    Dialog's text line color as a Long Integer.

    Table 30: Constants in the com.sun.star.util.NumberFormat constant group.

    Constant

    Value

    Description

    ALL

    All number formats.

    1

    DEFINED

    User-defined number formats.

    2

    DATE

    Date formats.

    4

    TIME

    Time formats.

    8

    CURRENCY

    Currency formats.

    16

    NUMBER

    Decimal number formats.

    32

    SCIENTIFIC

    Scientific number formats.

    64

    FRACTION

    Number formats for fractions.

    128

    PERCENT

    Percentage number formats.

    256

    TEXT

    Text number formats.

    6

    DATETIME

    Number formats that contain date and time.

    1024

    LOGICAL

    Boolean number formats.

    2048

    UNDEFINED

    Used if no number format exists.

  3. Set the FormatKey (see Table 29) to reference the desired format contained in the FormatsSupplier.

The number formatter that controls the formatting in the input box must be created by the number format supplier in the FormatsSupplier property. In other words, you can't simply take a number formatter created by the document or some other number formatter. When the formats supplier is searched to determine what numeric formats it contains, the constants in the NumberFormat constant group are used (see Table 30 ).

The formatted control model contains a number format supplier in the FormatsSupplier property. The supplier identifies its contained numeric formats based on a numeric key. The FormatKey property in Table 29 must be set with the key obtained from the FormatsSupplier. Use the methods in Table 31 to find or create the numeric format for the formatted control.

Table 31: Properties in the com.sun.star.awt.UnoControlFormattedFieldModel service.

Method

Description

getByKey(key)

Return the com.sun.star.util.NumberFormatProperties based on the numeric key.

queryKeys(NumberFormat, Locale, boolean)

Return an array of Long Integer keys that identify numeric formats of the specified type (see Table 30) for the specified locale. If the final Boolean parameter is True and if no formats exist, one will be created.

queryKey(format, Locale, boolean)

Return the Long Integer key for the specified format string.

addNew(format, Locale)

Add a number format and return the Long Integer key.

addNewConverted(format, Locale, Locale)

Add a number format, using a format string in a locale that is different than the desired locale.

removeByKey(key)

Remove a number format based on the Long Integer key.

generateFormat(key, Locale, bThousands, bRed, nDecimals, nLeading)

Return a format string based on the input values, but do not actually create the number format.

Note  

Add a formatted control to the OOMESample dialog.

Although it is not overly difficult to use the methods in Table 31 to find and create your own numeric formats, the easiest method to associate a formatted control to a numeric format object is to use the Properties dialog in the IDE. Add a formatted control to the dialog and name it MyFormattedField. The code in Listing 12 initializes the control to use the current date as its initial value and sets the desired date format. The date is formatted using the format "DD. MMM YYYY".

Listing 12: Set a formatted control to use a date as "DD. MMM YYYY".
start example
 REM Set the formatted field to a specific format.   Dim oFormats      'All of the format objects   Dim oSupplier     'All of the format objects   Dim nKey As Long  'Index of number format in the number formats   Dim oLocale as new com.sun.star.lang.Locale   Dim sFormat As String   sFormat = "DD. MMM YYYY"   oSupplier =oOOMEDlg.getModel().getByName("MyFormattedField").FormatsSupplier   oFormats  =oSupplier.getNumberFormats()   REM See if the number format exists by obtaining the key.   nKey = oFormats.queryKey(sFormat, oLocale, True)   REM If the number format does not exist, add it.   If (nKey = -1) Then     nKey = oFormats.addNew(sFormat, oLocale)     REM If it failed to add, and it should not fail to add, then use zero.     If (nKey = -1) Then nKey = 0   End If   REM Now, set the key for the desired date formatting.   REM I set this to treat the value as a number.   oOOMEDlg.getModel().getByName("MyFormattedField").FormatKey = nKey   oOOMEDlg.getModel().getByName("MyFormattedField").TreatAsNumber = True   REM I can set the date using a string or the date.   REM ....EffectiveValue = "12. Apr 2004"   REM But I can also use a date directly!   oOOMEDlg.getModel().getByName("MyFormattedField").EffectiveValue = Date() 
end example
 

There are a couple of interesting things to notice in Listing 12. First, the EffectiveValue property is used rather than the Text property. The TreatAsNumber property is set to True because the spin control does not properly increment an initial date if the TreatAsNumber property is set to False. Although it is not shown, the formatted control uses the same numeric values for dates as the Basic Date data type-unlike the Date control. Finally, the spin button in a formatted control always increments and decrements the value by 1-unlike the Date control, which can independently increment and decrement each portion of the date.

Pattern Control

Use a pattern control to enter formatted strings based on an edit mask and a literal mask. The literal mask is the string value that is initially displayed when the control starts. The user then edits the value in the control but is limited by the edit mask. The edit mask contains special characters that define what value can be entered at which location. For example, the character L (literal) indicates that the user cannot enter a value at the specified location, and the value N (number) indicates that the user can only enter the characters 0 through 9.

In the United States, each person is issued an identification number for tax purposes called a social security number. The social security number is composed of three numbers, a dash, two numbers, a dash, and three numbers. The edit mask is given as "NNNLNNLNNN". This allows the user to enter numeric values at the appropriate locations, but prevents any modifications where the dashes are located. A literal mask of the form "___-__-___" provides the initial template for the user to see, as illustrated in Listing 13 . The use of the character "_" is an arbitrary choice; you may use any value that you desire , such as a space character.

Listing 13: Edit mask and literal mask for a social security number.
start example
 EditMask    = "NNNLNNLNNN" LiteralMask = "___-__-___" 
end example
 

The number of characters that can be entered is determined by the length of the edit mask. It is considered an error if the edit mask and the literal mask are not the same length. Table 32 shows the edit mask characters supported by the pattern control. The pattern field supports the properties in Table 33 .

Table 32: Edit mask characters supported by the pattern control.

Character

Description

L

A text constant that is displayed but cannot be edited.

a

The characters a-z and A-Z can be entered.

A

The characters a-z and A-Z are valid, but the letters a-z are converted to uppercase.

c

The characters a-z, A-Z, and 0-9 can be entered.

C

The characters a-z, A-Z, and 0-9 are valid, but the letters a-z are converted to uppercase.

N

The characters 0-9 can be entered.

x

Any printable character can be entered.

X

Any printable character can be entered, but the letters a-z are converted to uppercase.

Table 33: Properties in the com.sun.star.awt.UnoControlPatternFieldModel service.

Property

Description

EditMask

The edit mask.

LiteralMask

The literal mask.

StrictFormat

If True, the text is checked during the user input.

Border

Specify no border (0), a 3-D border (1), or a simple border (2).

MaxTextLen

Maximum number of characters the control may contain. If zero, the text length is not purposely limited.

Printable

If True, the control is printed with the document.

ReadOnly

If True, the control's content cannot be modified by the user.

Tabstop

If True, the control can be reached by using the Tab key.

Text

The text that is displayed in the control.

BackgroundColor

Dialog's background color as a Long Integer.

Enabled

If True, the dialog is enabled.

FontDescriptor

FontDescriptor structure for the text in the dialog's caption bar.

FontEmphasisMark

FontEmphasis for the text in the dialog's caption bar.

FontRelief

FontRelief for the text in the dialog's caption bar.

HelpText

Dialog's help text as a String.

HelpURL

Dialog's help URL as a String.

TextColor

Dialog's text color as a Long Integer.

TextLineColor

Dialog's text line color as a Long Integer.

Tip  

If the StrictFormat property is False, the pattern control ignores the edit mask and the literal mask.

Fixed Text Control

Use the fixed text control to label other controls and areas in a dialog. In the IDE, the fixed text control is called a "label field." The fixed text control is a very simple text edit field. The model supports the properties in Table 34 .

Table 34: Properties in the com.sun.star.awt.UnoControlFixedTextFieldModel service.

Property

Description

Align

Specify that the text is aligned left (0), center (1), or right (2).

BackgroundColor

Control's background color as a Long Integer.

Border

Specify no border (0), a 3-D border (1), or a simple border (2).

Enabled

If True, the control is enabled.

FontDescriptor

FontDescriptor structure for the text in the control.

FontEmphasisMark

FontEmphasis for the text in the control.

FontRelief

FontRelief for the text in the control.

HelpText

Control's help text as a String.

HelpURL

Control's help URL as a String.

Label

Text label displayed in the control.

MultiLine

If True, the text may use more than one line.

Printable

If True, the control is printed with the document.

TextColor

Control's text color as a Long Integer.

TextLineColor

Control's text line color as a Long Integer.

File Control

The file control is a text edit control that contains a command button, which opens the File dialog. The initial directory that is used is set by the Text property. Table 35 contains the properties defined by the file control model.

Table 35: Properties in the com.sun.star.awt.UnoControlFileControlModel service.

Property

Description

BackgroundColor

Control's background color as a Long Integer.

Border

Specify no border (0), a 3-D border (1), or a simple border (2).

Enabled

If True, the control is enabled.

FontDescriptor

FontDescriptor structure for the text in the control.

FontEmphasisMark

FontEmphasis for the text in the control.

FontRelief

FontRelief for the text in the control.

HelpText

Control's help text as a String.

HelpURL

Control's help URL as a String.

Printable

If True, the control is printed with the document.

Text

The text displayed in the control.

TextColor

Control's text color as a Long Integer.

TextLineColor

Control's text line color as a Long Integer.

The file control is easy to use, but unfortunately it doesn't support using filters. A frequent solution for this is to add a text input box with a button next to it. When the button is selected, it opens a file selection dialog with the desired filters. When the dialog is closed, it adds the selected file to the text control.

Add a text field named FileTextField to the OOMESample dialog. Add a button next to the text field that calls the macro in Listing 14.

Listing 14: FileButtonSelected is in the DlgCode module in this chapter's source code files as SC17.sxw.
Note  
start example
 Sub FileButtonSelected   Dim oFileDlg           'File selection dialog   Dim oSettings          'Settings object to get the path settings   Dim oPathSettings      'Path to the settings object   Dim sFile As String    'File URL as a string   Dim oFileAccess        'Simple file access object   Dim oFiles             'The File dialog returns an array of selected files   REM Start with the value in the text field   sFile = oOOMEDlg.getModel().getByName("FileTextField").Text   If sFile <> "" Then     sFile = ConvertToURL(sFile)   Else     REM The text field is blank, so obtain the path settings     oSettings = CreateUnoService("com.sun.star.frame.Settings")     oPathSettings = oSettings.getByName("PathSettings")     sFile = oPathSettings.getPropertyValue("Work")   End If   REM Dialog to select a file   oFileDlg = CreateUnoService("com.sun.star.ui.dialogs.FilePicker")   REM Set the supported filters   oFileDlg.AppendFilter( "All files (*.*)", "*.*" )   oFileDlg.AppendFilter( "JPG files (*.jpg)", "*.jpg" )   oFileDlg.AppendFilter( "OOo Writer (*.sxw)", "*.sxw")   oFileDlg.AppendFilter( "OOo Calc (*.sxc)", "*.sxc")   oFileDlg.AppendFilter( "OOo Draw (*.sxd)", "*.sxd")   oFileDlg.AppendFilter( "OOo Impress (*.sxi)", "*.sxi")   oFileDlg.SetCurrentFilter( "All files (*.*)" )   REM Determine if the "file" is a directory or a file!   oFileAccess = CreateUnoService("com.sun.star.ucb.SimpleFileAccess")   If oFileAccess.exists(sFile) Then     REM I do not force the "display directory" to be a folder.     REM I could do something fancy with this such as     REM If NOT oFileAccess.isFolder(sFile) Then extract the folder...     REM but I won't!     oFileDlg.setDisplayDirectory(sFile)   End If   REM Execute the File dialog.   If oFileDlg.execute() Then     oFiles = oFileDlg.getFiles()     If UBound(oFiles) >= 0 Then       sFile = ConvertFromURL(oFiles(0))       oOOMEDlg.getModel().getByName("FileTextField").Text = sFile     End If   End If End Sub 
end example
 

Create a text field and name it FileTextField. Add a button next to the text field and set the "When initiating" event to call the macro in Listing 14 . This macro opens a file selection dialog based on the directory or file stored in the FileTextfield. If the text field is empty, the macro checks the configuration information to determine the starting directory. The interesting thing about this example is that it uses multiple file filters-something that isn't possible if a file control is used.

Image Control

An image control is used to display a graphic image. The image control is able to automatically scale an image to fit inside the image control. Use the ImageURL property to specify the image to load and the ScaleImage property to tell the control to scale the image automatically (see Table 36 ).

Table 36: Properties in the com.sun.star.awt.UnoControllmageControlModel service.

Property

Description

BackgroundColor

Control's background color as a Long Integer.

Border

Specify no border (0), a 3-D border (1), or a simple border (2).

Enabled

If True, the dialog is enabled.

HelpText

Control's help text as a String.

HelpURL

Control's help URL as a String.

ImageURL

URL of the image to load.

Printable

If True, the control is printed with the document.

ScaleImage

If True, the image is automatically scaled to the size of the control.

TabStop

If True, the Tab key can reach this control.

Progress Control

A progress bar is a straight bar that fills in a solid color starting at the left and moving to the right. The idea is that at the start the progress bar is empty, and it fills as work is accomplished. A typical example is the "Saving document" progress bar at the bottom of OpenOffice when you click the Save icon to save an open document.

Use the ProgressValueMin and ProgressValueMax properties to tell the control the range of values that it will contain. When the ProgressValue property is at the minimum value, the control is empty-nothing is filled. When the ProgressValue is halfway between the minimum and the maximum values, the control is half filled. Finally, when the ProgressValue is at the maximum value, the control is completely filled. The progress bar is not limited to the values of empty, full, and half; these values are only examples. Table 37 contains the properties supported by the progress control model.

Table 37: Properties in the com.sun.star.awt.UnoControlProgressBarModel service.

Property

Description

BackgroundColor

Control's background color as a Long Integer.

Border

Specify no border (0), a 3-D border (1), or a simple border (2).

Enabled

If True, the dialog is enabled.

FillColor

Color used to fill the progress bar.

HelpText

Control's help text as a String.

HelpURL

Control's help URL as a String.

Printable

If True, the control is printed with the document.

ProgressValue

Current progress value as a Long Integer.

ProgressValueMax

Maximum progress value as a Long Integer.

ProgressValueMin

Minimum progress value as a Long Integer.

Tip  

You can set both BackgroundColor and FillColor.

List Box Control

A list box contains a list of items-one per line-from which the user may select zero or more items. In other words, a list box provides a mechanism to select multiple items from a list. The list box control automatically adds scroll bars if they are required. Table 38 contains a list of properties supported by the list box model.

Table 38: Properties in the com.sun.star.awt.UnoControlListBoxModel service.

Property

Description

BackgroundColor

Control's background color as a Long Integer.

Border

Specify no border (0), a 3-D border (1), or a simple border (2).

Dropdown

If True, the control has a drop-down button.

Enabled

If True, the control is enabled.

FontDescriptor

FontDescriptor structure for the text in the control.

FontEmphasisMark

FontEmphasis for the text in the control.

FontRelief

FontRelief for the text in the control.

HelpText

Control's help text as a String.

HelpURL

Control's help URL as a String.

LineCount

The maximum line count displayed in the drop-down box.

MultiSelection

If True, more than one entry can be selected.

Printable

If True, the control is printed with the document.

ReadOnly

If True, the user cannot modify the data in the control.

SelectedItems

Array of Short Integers that represent the index of the selected items.

StringItemList

Array of strings that represent the items in the list box.

Tabstop

If True, the control can be reached by using the Tab key.

TextColor

Control's text color as a Long Integer.

TextLineColor

Control's text line color as a Long Integer.

Although I recommend doing most manipulations through the model, many things are frequently done using methods defined for the control. The list box control supports the same special functions supported by the combo box control (see Table 18) to add and remove items at specific locations. The list box control supports other useful methods that are primarily related to the user interaction (see Table 39 ).

Table 39: Methods defined by the com.sun.star.awt.XListBox interface.

Method

Description

add Item Listener(XItemListener)

Add a listener for item events.

removeItemListener(XItemListener)

Remove a listener for item events.

addActionListener(XActionListener)

Add a listener for action events.

removeActionListener(XActionListener)

Remove a listener for action events.

addItem(String, position)

Add an item at the specified position.

addItems(StringArray, position)

Add multiple items at the specified position.

removeItems(position, count)

Remove a number of items at the specified position.

getItemCount()

Get the number of items in the list box.

getItem(position)

Get the specified item.

getItems()

Return the StringItemList property (see Table 38).

getSelectedItemPos()

Return the position of one of the selected items. This is useful if only one item can be selected.

getSelectedItemsPos()

Return the Selectedltems property (see Table 38).

getSelectedItem()

Return one of the selected items. This is useful if only one item can be selected.

getSelectedItems()

Return all selected items as an array of strings.

selectItemPos(position, boolean)

Select or deselect the item at the specified position.

selectItemsPos( positions , boolean)

Select or deselect multiple items at the positions specified by the array of positions.

selectItem(item, boolean)

Select or deselect the specified item string.

isMutipleMode()

Get the MultiSelection property (see Table 38).

setMultipleMode(boolean)

Set the MultiSelection property (see Table 38).

getDropDownLineCount()

Get the LineCount property (see Table 38).

setDropDownLineCount(integer)

Set the LineCount property (see Table 38).

makeVisible(position)

Scroll the items in the list box so that the specified item is visible.

Tip  

If using a language other than OOo Basic, it is important to note that all of the integer arguments in Table 39 are Short Integers.

Scroll Bar Control

The scroll bar control can be used to scroll a control or dialog that does not already contain or support a scroll bar. All of the work to control another object and synchronize the external object with the scroll bar must be done using a macro. In other words, the scroll bar control does not automatically connect to or control another object, but requires a macro to implement the connection. To use the scroll bar control, write a macro that responds to the control's events and then manipulate another object based on what happens in the control. If you want the scroll bar to track changes in the controlled object, you must write handlers for the other object to update the scroll bar. As an input or an output, the scroll bar serves to indicate a relationship in another object; the relationship displayed and the corresponding action depends on the programming of a macro. See Table 40 .

Table 40: Properties in the com.sun.star.awt.UnoControlScrollBarModel service.

Property

Description

Blocklncrement

Increment for a block move as a Long Integer.

Border

Specify no border (0), a 3-D border (1), or a simple border (2).

Enabled

If True, the control is enabled.

HelpText

Control's help text as a String.

HelpURL

Control's help URL as a String.

Linelncrement

Increment for a single-line move as a Long Integer.

Orientation

Scroll bar orientation with values com.sun.star.awt.ScrollBarOrientation.HORIZONTAL (0) and com.sun.star.awt.ScrollBarOrientation.VERTICAL (1).

Printable

If a scroll bar is embedded into a document, setting this to True causes the scroll bar to be printed when the document is printed.

ScrollValue

Current scroll value.

ScrollValueMax

Maximum scroll value of the control.

VisibleSize

Visible size of the scroll bar.

Add a horizontal scroll bar to the OOMESample dialog. Add the global variable oBPosSize to store a button's original position and size (see Listing 15).

Listing 15: Global variables for the Close button's initial position and size.
Note  
start example
 Dim oBPosSize    'Button original position and size 
end example
 

To illustrate how the scroll bar functions, add a horizontal scroll bar to the sample dialog and name it ButtonScrollBar. All of the work done by a scroll bar control is done by a macro. A scroll bar doesn't know if something is horizontal or vertical, so it's just as easy to use a vertical scroll bar as a horizontal scroll bar for the same application-a person using a vertical scroll bar to move something horizontally might face ridicule by his peers, but the control doesn't care. I chose a horizontal scroll bar because I want to use it to move the Close button horizontally on the dialog. Add a global variable to store the initial position of the Close button (see Listing 15 ).

In my sample dialog, there is nothing between the Close button and the right edge of the dialog (see Figure 7 ). I want the scroll bar to cause the Close button to move right and left.

The maximum scroll bar value defaults to 100. This is usually used as a percentage to scroll something. In the sample dialog, however, I calculate the maximum distance that I can move the Close button, and then I set the maximum value that the scroll bar can return as this number. This allows me to use the scroll value directly, rather than calculating a position based on a percentage, which is the usual case.

In the initialization section, add code that saves the Close button's initial position and size (see Listing 16 ); this information is used later as a reference point. Next, calculate how far the button can be shifted to the right based on the size and position of the button and the size of the dialog that contains the button.

Listing 16: Save the initial button position and set the scroll bar's maximum value.
start example
 REM Get the Close button's original position and size.   REM Set the maximum value that the scroll bar can become   REM based on the maximum distance that I can move the Close button.   oBPosSize = oOOMEDlg.getControl("CloseButton").getPosSize()   oOOMEDlg.getModel().getByName("ButtonScrollBar").ScrollValueMax = _        oOOMEDlg.getPosSize.Width - oBPosSize.X - oBPosSize.Width - 10 
end example
 

Set the scroll bar to call the ScrollButton method in Listing 17 for the "While Adjusting" event. The ScrollButton method uses the scroll value to position the Close button.

Listing 17: ScrollButton is in the DlgCode module in this chapter's source code files as SC17.sxw.
start example
 Sub ScrollButton   Dim oModel       'Scroll bar model   Dim oButton      'Close button   Dim newX As Long 'New X location for the Close button   oModel = oOOMEDlg.getModel().getByName("ButtonScrollBar")   oButton = oOOMEDlg.getControl("CloseButton")   REM The scroll bar was set so that its maximum value is   REM the maximum desired value.   newX = oBPosSize.X + oModel.ScrollValue   oButton.setPosSize(newX, 0, 0, 0, com.sun.star.awt.PosSize.X) End Sub 
end example
 

Now you can move the Close button to the right and to the left by moving the scroll bar.




OpenOffice.org Macros Explained
OpenOffice.org Macros Explained
ISBN: 1930919514
EAN: 2147483647
Year: 2004
Pages: 203
Authors: Andrew Pitonyak
BUY ON AMAZON

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net