Õ¾ÄÚËÑË÷: ÇëÊäÈëËÑË÷¹Ø¼ü´Ê
µ±Ç°Ò³Ãæ: ͼÊéÊ×Ò³ > SWT: The Standard Widget Toolkit

8.1 Classes ToolBar and ToolItem - SWT: The Standard Widget Toolkit

Previous Section  < Day Day Up >  Next Section

8.1 Classes ToolBar and ToolItem

8.1.1 Example

graphics/08inf01.gif

8.1.2 ToolBar and ToolItem Hierarchies

graphics/08inf02.gif

8.1.3 ToolBar Styles

Style

Description

SWT.WRAP

Wrap the buttons to fit the visible area

SWT.FLAT

Draw the tool bar with a flat look

SWT.HORIZONTAL

Layout buttons from left to right

SWT.VERTICAL

Layout buttons from top to bottom

SWT.RIGHT

Place the text in each item to the right in the item

SWT.SHADOW_OUT

Draw a separator above the tool bar


8.1.4 ToolBar Events (none)

Event

Description


8.1.5 ToolItem Styles

Style

Description

SWT.PUSH

Create a push button tool item

SWT.CHECK

Create a check button tool item

SWT.RADIO

Create a radio button tool item

SWT.SEPARATOR

Create a separator tool item

SWT.DROP_DOWN

Create a drop-down tool item


8.1.6 ToolItem Events

Event

Description

SWT.Selection

The tool item was selected


Tool bars are used to display horizontal or vertical rows of tool bar buttons represented by instances of the class ToolItem. Tool bars are often placed just below the main menu bar at the top of the shell.[1] When resized, tool bars are responsible for automatically positioning and resizing their tool items.[2] Creating a tool bar with the style SWT.HORIZONTAL causes the items to be displayed in rows. The SWT.VERTICAL style is used to display the items in columns.

[1] Of course, on the Macintosh, the main menu bar is not in the shell.

[2] ToolBar is often used in conjunction with the classes CoolBar and CoolItem (see Classes CoolBar and CoolItem). This combination allows the user to rearrange tool bars dynamically with the mouse. Tool bars by themselves do not provide this capability.

Tool items are analogous to push buttons and menu items, supporting similar creation styles and listeners. They are automatically added to the list of items in a tool bar when they are created. The position index parameter in the ToolItem constructor can be used to create an item at a specific index, relative to the other items in the tool bar. If a position index is not provided, the item is added to the end of the list. ToolBar does not implement a remove() or setVisible() operation. Items are removed and hidden when their dispose() method is called.

Tool items, like buttons, can display strings and images. Surprisingly, tool items are also used to represent the spacing between items, behaving as separators. Separators cannot be selected and do not draw strings or images.

A drop-down tool item is a special kind of item that behaves similar to a combo, allowing the user to select a small drop-down indicator. Often, a program will display a menu or list when the indicator is selected.

The following fragment creates a horizontal tool bar and adds three tool items. One item represents a cut operation, one a copy operation, and the last, a paste operation:






ToolBar toolBar = new ToolBar(parent, SWT.HORIZONTAL);

ToolItem cutItem = new ToolItem(toolBar, SWT.PUSH);

cutItem.setImage(cutImage);

ToolItem copyItem = new ToolItem(toolBar, SWT.PUSH);

copyItem.setImage(copyImage);

ToolItem pasteItem = new ToolItem(toolBar, SWT.PUSH);

pasteItem.setImage(pasteImage);


Tool items often provide quick access to actions that also appear somewhere on the main menu. When first introduced and used in this capacity, they were sometimes called smart icons. When used as smart icons, tool items play the same role as accelerators, providing quick access to menu operations. However, access is provided using the mouse instead of the keyboard.

Tool Tips to the Rescue!

A funny thing happened when smart icons were introduced. When too many were used within a program, some people found them overwhelming. The problem was that users couldn't immediately figure out which operations they performed. Despite valiant attempts by user interface designers, pictures can be ambiguous. (In this case, a picture is not worth 1,000 words.)

Contrast this with menus. New users often spend time examining (but not invoking) the menus in a program to see what the program can do. Fortunately, tool tips were invented to allow new users to do the same thing with tool bars. When the mouse is hovered over a tool item, a short descriptive message roughly equivalent to the text that might have appeared in a menu item is displayed.

See the section Tool Item Tool Tips to make sure that the tool items you create provide tool tips. Otherwise, your smart icons might frustrate the user.


8.1.7 Tool Items That Act Like Buttons

Tool items that support text and images use the same API as buttons. Just like the Button class, ToolItem does not support wrapping or SWT.WRAP (although the ToolBar class does support SWT.WRAP to wrap the tool items). More than one line of text in a tool item is not supported.

setText(String string) Sets the text for the item. The string may include mnemonic characters but cannot include line delimiters. Setting the text of the item causes the tool bar to reposition its items.

getText() Returns the text for the item. This is an empty string if the text has never been set or if the tool item is a separator.

setImage(Image image) Sets the image for the item. Setting the image of a tool item causes the tool bar to reposition its items.

The First Image Defines the Size of All Images in the Control

Many of the controls in SWT that support multiple images scale all of the images they display to be the same size. By definition, this is the size of the first image inserted into the control. This restriction is a direct result of a limitation of Microsoft Windows and cannot be worked around in SWT. The controls that are affected are ToolBar, TabFolder, Tree, and Table.


getImage() Returns the image for the item. This is null if the image has never been set or if the item is separator.

ToolItem supports the SWT.PUSH, SWT.CHECK, and SWT.RADIO styles. When a tool item is created with one of these styles, it behaves in the same manner as a button with the equivalent style.

Tool items created with the SWT.CHECK style stay selected after the user has clicked on them. Tool items created with SWT.RADIO, when grouped together, behave like radio buttons. Check or radio tool items allow you to set their selection state using setSelection().

setSelection(boolean selection) Sets the selection state for the item.

getSelection() Returns a boolean that is the selection state of the item.

The following example creates six tool items with the styles SWT.CHECK, SWT.PUSH, and SWT.RADIO. The result is shown in Figure 8.1.






public static void main(String[] args) {

    Display display = new Display();

    Shell shell = new Shell(display);

    ToolBar toolBar = new ToolBar(shell, SWT.HORIZONTAL);

    for (int i = 0; i < 2; i++) {

        ToolItem item = new ToolItem(toolBar, SWT.CHECK);

        item.setText("Check " + i);

    }

    for (int i = 0; i < 2; i++) {

        ToolItem item = new ToolItem(toolBar, SWT.PUSH);

        item.setText("Push " + i);

    }

    for (int i = 0; i < 2; i++) {

        ToolItem item = new ToolItem(toolBar, SWT.RADIO);

        item.setText("Radio " + i);

    }

    toolBar.pack();

    shell.pack();

    shell.open();

    while (!shell.isDisposed()) {

        if (!display.readAndDispatch()) display.sleep();

    }

    display.dispose();

}


Figure 8.1.

graphics/08fig01.gif


A radio group of tool items is formed when one radio tool item is placed next to another. It is possible to create multiple groups of radio items in one tool bar by separating radio items with items that do not have the SWT.RADIO style.[3] This differs from the behavior of radio buttons in composites, where there is only ever one radio group, no matter how the buttons are separated.[4] ToolBar supports the SWT.NO_RADIO_GROUP style to allow you to disable radio behavior but application programs rarely use it.

[3] Multiple radio groups are supported in menus in the same manner, using menu items created with SWT.RADIO.

[4] We actually tried to change this behavior to be consistent with tool items between SWT 1.0 and 2.0 but it broke Eclipse.

8.1.8 Tool Items That Act Like Separators

Tool items with the style SWT.SEPARATOR serve two purposes. The most obvious use is to provide spacing between items. However, they are also used to position any control within a tool bar, as seen below. In both cases, the width of the separator tool item is specified using setWidth().

setWidth(int width) Sets the width of the separator item and causes the tool bar to reposition the items to take into account the new width.

getWidth() Returns the width of the tool item.

The following example creates a tool bar with a combo control, followed by two separators and two push button tool items. Because it is not an instance of ToolItem, a combo cannot truly be an item in a tool bar. Instead, it is placed on top of the first separator tool item using setControl(). The result is shown in Figure 8.2.






public static void main(String[] args) {

    Display display = new Display();

    Shell shell = new Shell(display);

    ToolBar toolBar = new ToolBar(shell, SWT.HORIZONTAL);

    Combo combo = new Combo(toolBar, SWT.READ_ONLY);

    ToolItem comboItem =

        new ToolItem(toolBar, SWT.SEPARATOR);

    comboItem.setControl(combo);

    comboItem.setWidth(64);

    new ToolItem(toolBar, SWT.SEPARATOR);

    for (int i = 0; i < 2; i++) {

        ToolItem item = new ToolItem(toolBar, SWT.PUSH);

        item.setText("Push " + i);

    }

    toolBar.pack();

    shell.pack();

    shell.open();

    while (!shell.isDisposed()) {

        if (!display.readAndDispatch()) display.sleep();

    }

    display.dispose();

}


Figure 8.2.

graphics/08fig02.gif


Placing a combo on top of a tool item seems a little strange but is the direct result of the fact that tool items are not controls. It is not possible to include them in the items list of a tool bar because that list can contain only tool items.[5]

[5] Ah, the joys of strongly typed languages.

The setControl() method is used to associate a control with a tool item.

setControl(Control control) Sets the control that will be positioned on top of the tool item when it has the SWT.SEPARATOR style. When the tool bar positions the separator item, the control is moved and resized accordingly.

getControl() Returns the control that will be positioned on top of the tool item when the item has the style SWT.SEPARATOR.

8.1.9 Tool Items That Drop Down

Tool items, when created with the style SWT.DROP_DOWN, provide a "drop-down arrow" that can be selected by the user like a combo control. One big difference between a combo and a drop-down tool item is the fact that the drop-down list is not provided automatically by the tool item. This allows the application code to display any kind of control for the item.

When the user selects the drop-down arrow, an SWT.Selection event is issued. The detail field of the event is set to SWT.ARROW to indicate that the arrow was pressed. A drop-down tool item can also be selected outside of the drop-down arrow indicator. In this case, the detail field is zero.

The following example code displays a menu using a drop-down tool item, as shown in Figure 8.3.






public static void main(String[] args) {

    final Display display = new Display();

    Shell shell = new Shell(display);

    final ToolBar toolBar =

        new ToolBar(shell, SWT.HORIZONTAL);

    final Menu menu = new Menu(shell, SWT.POP_UP);

    for (int i = 0; i < 8; i++) {

        MenuItem item = new MenuItem(menu, SWT.PUSH);

        item.setText("Item " + i);

    }

    final ToolItem item =

        new ToolItem(toolBar, SWT.DROP_DOWN);

    item.setText("Drop Down");

    item.addListener(SWT.Selection, new Listener() {

        public void handleEvent(Event event) {

            if (event.detail == SWT.ARROW) {

                Point point = new Point(event.x, event.y);

                point = display.map(toolBar, null, point);

                menu.setLocation(point);

                menu.setVisible(true);

            }

        }

    });

    toolBar.pack();

    shell.pack();

    shell.open();

    while (!shell.isDisposed()) {

        if (!display.readAndDispatch()) display.sleep();

    }

    display.dispose();

}


Figure 8.3.

graphics/08fig03.gif


The x and y coordinates provided in the event should be used to position the widget that you create. By using these coordinates, your widget will appear at the correct location, relative to the tool item.

8.1.10 Tool Item Bounds

Sometimes you might need to query the bounds of a tool item, possibly to determine whether it is visible in a tool bar. When a tool bar is resized to be too small to show all the items, they are clipped. The bounds of each item can be compared against the client area of the tool bar to see which items are clipped.

To find out the bounds of a tool item, the getBounds() method is used.

getBounds() Returns a rectangle that describes the location and size of the item, relative to its parent.

8.1.11 Tool Item Tool Tips

Tool tips are short, descriptive messages that appear when the user hovers the mouse over a widget. Tool tips are supported for tool items using the setToolTipText() method.

setToolTipText(String string) Sets the tool tip text for the item. This string is displayed when the user hovers with the mouse over the item.[6] Setting this string to null removes the tool tip.

[6] The user doesn't actually hover in the "flying carpet" sense of the word!

getToolTipText() Returns the tool tip text.

Note that the duration, location, and mouse gesture that triggers the tool tip are all platform-specific.

8.1.12 Enabling and Disabling Tool Items

Even though they are not controls, tool items can be enabled and disabled, just like controls. If you consider that tool items behave a lot like buttons and menu items, then the ability to enable and disable a tool item is an important feature.

setEnabled(boolean enabled) Enables or disables the item, depending on the boolean argument. A disabled item is not selectable in the user interface and draws using a "grayed" look.

getEnabled() Returns the enabled state of the item.

isEnabled() Returns true if the item is enabled, the tool bar that contains it is enabled, and all of the ancestors of the tool bar are enabled; otherwise, it returns false.

8.1.13 Disabled and Hot Images

The ToolItem class supports three different types of images. The first type of image, which was described in the section Tool Items That Act Like Buttons, is called the normal image. This image is assigned using setImage() and behaves as you might expect.

The second type of image is called the disabled image. This image is displayed whenever a tool item is disabled by a call to setEnabled(false).

setDisabledImage(Image image) Sets the image to be displayed in a tool item when the tool item is disabled. Setting this image to null causes the tool item to use the normal image, graying it appropriately when the item is disabled.

getDisabledImage() Returns the disabled image.

The disabled image can be very useful when the platform-specific algorithm that is used to gray the normal image behaves poorly, producing a "gray but mangled" image. This can happen when the graying algorithm is sensitive to the colors in your image. Setting the disabled image overrides the algorithm, ensuring that a disabled tool item draws using an image that looks good because it uses an image that you constructed.

The third type of image is called the hot image. The hot image is displayed when the mouse enters a tool item. When the mouse exits, the normal image is restored.

setHotImage(Image image) Sets the image to be displayed in the tool item when the mouse is inside the item. Setting this image to null causes the tool item to use the normal image.

getHotImage() Returns the hot image.

Hot images are generally less useful than disabled images. They represent a particular user interface look made popular by Windows 98, which is now generally abandoned, even on Windows.

Is the Tool Item Disabled?

Windows 98 and versions of Internet Explorer at the time used hot images to draw attention to the fact that the mouse had entered a tool item. The hot images were typically full color, whereas the normal images were grayscale. The problem with this approach was that the grayscale images looked too much like disabled images. Users couldn't tell when a tool item was disabled. It was this kind of ambiguity that probably caused hot images in tool bars to be abandoned.


8.1.14 Tool Bars That Wrap

When a tool bar is created with the style SWT.WRAP, it will wrap tool items when there is insufficient space to fit the items on a single row. The algorithm that is used to wrap tool items is platform-specific.[7] When a tool bar wraps, the number of rows in the tool bar increases. You can query the number of rows in a tool bar using getRowCount().

[7] For example, Windows keeps certain kinds of items together, most notably radio items. Separators are used as hints to indicate when to wrap to the next item.

getRowCount() Returns the number of rows in a tool bar. This method normally returns the integer 1, but it will return an integer between 2 and the number of items in the tool bar if the items are wrapped.

Sometimes, even though the tool bar was created with the SWT.WRAP style, when the tool bar is positioned by a layout (see the chapter Layout), the tool items do not seem to wrap. For a detailed discussion of this issue, see Forcing Controls to Wrap.

8.1.15 Tool Bars That Are Flat

To create a tool bar that draws with a "flat look," use the style SWT.FLAT. A flat tool bar generally does not draw push button borders for the items until the mouse moves over an item. The flat look of a tool bar is defined by the operating system theme.

These days, most programs use flat tool bars. Unfortunately, SWT.FLAT is not the default style in SWT. This is regrettable because applications that do not use flat tool bars can look dated.[8]

[8] We could possibly have fixed this problem by defining a new constant, such as SWT.RAISED or SWT.NOT_FLAT, and changing the default. Unfortunately, this kind of change would break too many application programs.

The Flat Look Is Back?

User interface fads come and go. Early versions of X/Motif sported a Romanesque, "chiseled" look. Menus resembled slabs of stone. Lists had huge, beveled borders. The first Macintoshes and Windows 2.0 had a "sheet of paper" look with oval buttons that were filled and flashed when you selected them. OS/2 and Windows 3.0 introduced 3D buttons and scroll bars. This was sometimes called the "2 1/2D" look because only some controls were 3D. By the time Windows 95 was released, chiseling and the 3D look were back. But then, users began to realize that excess borders and chiseling took up too much space. With the advent of the World Wide Web, the flat look is back. Who knows what will happen in the future? Perhaps antialiasing and transparency will become prevalent, giving birth to the "smeared look."


8.1.16 The Separator above the Tool Bar

Many applications include a tool bar that is positioned at the top of the window, under the menu bar. Visually, the tool bar is often separated from the menu bar by a separator. Early SWT programs emulated this behavior by placing a label with the styles SWT.SEPARATOR and SWT.SHADOW_OUT between the two widgets. This approach worked reasonably well on Windows but failed elsewhere. On the Macintosh, where the desktop provides a single menu bar that is shared by every application, the separator looked particularly strange.

To get around this platform difference, the SWT.SHADOW_OUT style was defined for ToolBar. This style causes tool bars to draw the appropriate separator. On the Macintosh and platforms that do not support this look, the separator is not drawn.

8.1.17 Searching and Hit Test Operations

The ToolBar class provides a number of searching and "hit test" operations that allow you to find items and indices.

getItem(int index) Returns the item at the index, which is zero-based. If the index is out of range, an IllegalArgumentException ("Index out of bounds") is thrown.

getItem(Point point) Returns the item under a point. The point is relative to the origin of the control.

getItemCount() Returns the number of items in the tool bar.

getItems() Returns an array of the items. This is a copy so that modifying it has no effect on the control.

indexOf(ToolItem item) Returns the zero-based index of the item. If the item is not found, –1 is returned.

8.1.18 ToolItem Events

SWT.Selection (SelectionEvent)

The SWT.Selection event (typed event SelectionEvent) is sent whenever the user selects an item with the mouse or the keyboard. The event fields relevant during a selection event for an instance of ToolItem are as follows.

Public Fields of Class Event That Are Valid during SWT.Selection

Field

Description

detail

This field contains SWT.ARROW if the drop-down indicator of a drop-down tool item was selected.

x

The x coordinate to be used when positioning a widget for a drop-down tool item. Note that this value is in the coordinate system of the tool bar.

y

The y coordinate to be used when positioning a widget for a drop-down tool item. Note that this value is in the coordinate system of the tool bar.


Note that the x and y coordinates almost always need to be translated to the coordinate system of the display. This is because the drop-down widget that you display is usually a shell or menu. See the map() method described in the chapter Display.

Using SWT.Selection to Implement a Drop-Down ToolItem

A good example that uses the SWT.Selection event with a drop-down tool item can be found in the section Tool Items That Drop Down.

    Previous Section  < Day Day Up >  Next Section