站内搜索: 请输入搜索关键词
当前页面: 图书首页 > SWT: The Standard Widget Toolkit

7.2 Class Button - SWT: The Standard Widget Toolkit

Previous Section  < Day Day Up >  Next Section

7.2 Class Button

7.2.1 Examples

graphics/07inf03.gif

graphics/07inf04.gif

7.2.2 Button Hierarchy

graphics/07inf05.gif

7.2.3 Button Styles

Style

Description

SWT.ARROW

Draw an arrow instead of text or an image

SWT.CHECK

Create a check button

SWT.PUSH

Create a push button

SWT.RADIO

Create a radio button

SWT.TOGGLE

Create a toggle button

SWT.FLAT

Draw the button with a flat look

SWT.UP

Draw an up arrow

SWT.DOWN

Draw a down arrow

SWT.LEFT

Left-align the button (or draw a left arrow)

SWT.RIGHT

Right-align the button (or draw a right arrow)

SWT.CENTER

Center align the button


7.2.4 Button Events

Event

Description

SWT.Selection

The button was selected


Buttons are simple controls that are commonly found in desktop applications. Aside from their appearance, buttons are fundamentally different from labels: Unlike labels, buttons are active. They react when the user clicks on them and issue events.

Where Are All the Button Classes?

Most widget toolkits provide a hierarchy of Button classes that map to the various kinds of operating system buttons. SWT provides one Button class and uses style bits to specify the appearance and behavior of Button instances. This same approach is used by the native button control on Windows, but more important, it reduces the number of classes needed to represent a similar concept. Reducing the number of classes in the toolkit is one of the design goals of SWT. Fewer classes lead to faster startup times and a smaller memory footprint. There are also fewer classes for you to learn.


7.2.5 Text and Images

Buttons support text and images using methods with the same signatures as Label. One interesting difference between strings in Button versus Label is that Button does not support SWT.WRAP or the linefeed character. This means that more than one line of text cannot be displayed in a button. Like labels, buttons can display either text or an image but not both at the same time (see the Text or Image but Not Both box earlier in this chapter for details).

setText(String string) Sets the text of the button. This string may include mnemonic characters (see Specifying the Mnemonic Character) but cannot include line delimiters.

getText() Returns the button text. This is an empty string if the text has never been set.

setImage(Image image) Sets the image for a button.

getImage() Returns the button image. This is null if the image has never been set.

Despite the fact that images are supported, buttons that display images are generally uncommon. Tool bars are almost always used instead (see Classes ToolBar and ToolItem).

7.2.6 Alignment

You can horizontally align the button text or the image using one of the SWT .LEFT, SWT.CENTER, or SWT.RIGHT style bits, or the setAlignment() method.

setAlignment(int alignment) Sets the alignment of the control to be left-, center-, or right-aligned, depending on the argument, which must be one of SWT.LEFT, SWT.CENTER, or SWT.RIGHT.

getAlignment() Returns the alignment of the control.

Button alignment is something that is rarely used in programs. Normally, you should not override the default alignment of a button because the default matches the standard appearance for the operating system. If you change the alignment of the buttons in your application, it may look out of place.

7.2.7 Push Buttons

Push buttons are created using the style SWT.PUSH. They are often used within a program to launch an action. For example, programs often use push buttons to allow the user to move forward in a wizard dialog, choose Yes in a message box, or to get more details in an error dialog.

When pushed, buttons draw in a pressed state. The user normally releases it at once, causing it to return to an unpressed state. If the mouse is released inside a button, an SWT.Selection event is issued. Application programs use this event to launch an action. Unlike other buttons, push buttons do not maintain their selected or unselected state between SWT.Selection events. They are considered to be always unselected.

The following code fragment creates a push button and sets the text to the string "Ok".






Button button = new Button(parent, SWT.PUSH);

button.setText("Ok");


7.2.8 Check Buttons

Check buttons are created with the style SWT.CHECK. They differ from push buttons in that they maintain a boolean selection state.[6] The user toggles the selection state of a check button using the mouse or the keyboard.

[6] Outside of SWT, the selection state of a check button is more commonly called the checked or unchecked state.

The appearance of a selected check button varies between platforms. For example, on some platforms, a check button draws an x when selected, whereas on others it draws a diamond.

You can set the selection state of a check button using the setSelection() method.

setSelection(boolean selection) Sets the selection state for the button. If the button is a check, radio, or toggle button, the new selection is assigned.

getSelection() Returns a boolean that is the selection for the button.

The following code fragment creates a check button, sets the text to the string "Overwrite when typing", then selects the button, causing it to be checked.






Button button = new Button(parent, SWT.CHECK);

button.setText("Overwrite when typing");

button.setSelection(true);


Calling setSelection() Does Not Cause an SWT.Selection Event

Programmers new to SWT often find this behavior confusing. After a long and arduous debate within the SWT community, it was decided that sending the event caused more problems than it solved. For example, if the SWT.Selection event were to be sent from setSelection(), multiple calls to this method would cause the listeners to run for each call, causing potential performance problems. As a result, it was decided that in SWT, setSelection() would not cause an SWT.Selection event.


Check buttons are mainly used to represent boolean state in a program. Very often, check buttons can be found in "preference" dialogs. Preference dialogs show the user the options available in a program and those that are selected. Although check buttons issue the SWT.Selection event when the user selects them, unlike push buttons, this event is generally not used to invoke an action. In the case of the preferences dialog, the action that accompanies the change in selection is performed when the dialog is closed (or when an apply push button in the dialog is pressed).[7]

[7] On the Macintosh, well-behaved programs do not do this. Instead, options are applied as the user selects them in the dialog. If you want to implement the Macintosh behavior, you can do so by watching for SWT.Selection events and invoking the action right away.

When a group of check buttons appears together, selecting one check button in the group does not affect the selection state of others.

7.2.9 Radio Buttons

Radio buttons, created using the SWT.RADIO style, are common user interface elements. Like check buttons, they maintain a boolean state between selections. However, when multiple radio buttons have the same parent, only one button can be selected at a time. When the user selects another radio button, the previous radio button loses its selection state. This is called radio behavior.[8]

[8] It is very likely that the term radio refers to the row of buttons that were found on the car radios of the '50s and '60s. These buttons also exhibited the behavior that only one could be pressed at a time.

The following code creates three radio buttons that allow the user to configure the word wrap state of a hypothetical text editor.






Button button1 = new Button(parent, SWT.RADIO);

button1.setText("Don't wrap");

button1.setSelection(true);

Button button2 = new Button(parent, SWT.RADIO);

button2.setText("Wrap to window");

Button button3 = new Button(parent, SWT.RADIO);

button3.setText("Wrap to ruler");


Radio buttons typically represent enumerations in a program. For example, in the code fragment above, they could be used to indicate three possible word wrap states of a text editor. Although not necessarily the case, in the source code for the editor, there would probably be an enumeration for the three wrap states and a variable to keep track of the current state. If this were the case, the following code fragment could be used to initialize the state of each radio button.






button1.setSelection(wrap == WRAP_NONE);

button2.setSelection(wrap == WRAP_WINDOW);

button3.setSelection(wrap == WRAP_RULER);


When to Use a Radio Button

Using a single radio button is almost certainly an error. Given that only one radio button in a group can be selected, the button will always be selected. In this case, a check button should be used instead.

Two radio buttons can be replaced by one check button. This is because a boolean and an enumeration with two states are equivalent. Of course, there are cases where it makes more sense to use two radio buttons instead of a single check button. For example, two radio buttons that offer a choice between "Red " or "Green" make more sense than a single check button to turn "Red " on or off.

Unfortunately, radio buttons can use lots of screen space. For example, an enumeration that contains 10 states will require 10 radio buttons. To minimize the required screen space, sometimes a read-only combo box is used in place of multiple radio buttons (see the Combo section).


If for some reason you need radio buttons that do not have radio behavior, the SWT.NO_RADIO_GROUP style, when specified on the parent, allows you to disable it. This style is almost never used because radio buttons without radio behavior are confusing to the user.

7.2.10 Toggle Buttons

Toggle buttons are push buttons that remain pressed when selected. They are created with the style SWT.TOGGLE.






Button button = new Button(parent, SWT.TOGGLE);

button.setText("Play");

button.setSelection(true);


Toggle buttons should generally be avoided. Before tool bars were invented, toggle buttons and push buttons were sometimes used to implement tool bar behavior. Programs that do this today look dated.

Because toggle buttons maintain their selection, every place you might use a toggle button, a check button can be used instead. Probably the only place where a toggle button might be useful is to model a physical button that is expected to stay pressed. For example, a toggle button would look better than a check button when implementing a software DVD player.

7.2.11 Arrow Buttons

Arrow buttons are buttons that draw a small, arrow-shaped icon. The arrow shape is platform-specific and is not guaranteed to match the arrow part of a scroll bar, although it is often similar.

Arrow buttons are created with the style SWT.ARROW. They can be made to point in one of four directions using the constants SWT.LEFT, SWT.RIGHT, SWT.UP, and SWT.DOWN.






Button button = new Button(parent, SWT.ARROW);

button.setAlignment(SWT.RIGHT);


Arrow buttons are uncommon. Occasionally, they are used to allow users to navigate through data one page at a time. More often, operations such as "next page" and "previous page" are presented to the user as icons on a tool bar.

7.2.12 Button Events

SWT.Selection (SelectionEvent)

The SWT.Selection event (typed event SelectionEvent) is sent when the user clicks on a button with the mouse or activates it with the keyboard. The space bar or <Enter> key usually activates a button (but this is not guaranteed on all platforms). The selection event for Button contains meaningful values in only the display, widget, and type fields.

The following code fragment prints "Ok Pressed" when a button is selected.






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

    public void handleEvent(Event event) {

        System.out.println("Ok Pressed");

}

});


Sometimes programmers are confused by the fact that SWT.Selection is sent whenever the user causes the state of a button to change. The rationale should be obvious with some reflection, but the result has subtle implications for radio buttons.

Using SWT.Selection with Radio Buttons

First of all, SWT.Selection is rarely used with radio buttons. Like check buttons, radio buttons often appear in dialogs. On most operating systems, programs do not take action until the dialog is closed.

Surprisingly, when the user selects a radio button in a group of radio buttons, two SWT.Selection events are sent. The previously selected radio button receives an SWT.Selection event indicating that the selection state has been changed to false. The newly selected radio button gets an SWT.Selection event to indicate that its selection state is now true. It sometimes helps to understand why there are two SWT.Selection events if you imagine for a moment that radio buttons did not support radio behavior. Hypothetically, the first event would be generated when the user clicked to "turn off" the first radio button, and the second event would be generated when the user clicked to "turn on" the second button.

If you want to perform an action when the user selects a radio button, you almost always need to get the selection before performing the action. The following code fragment uses getSelection() to ensure that the arriving message is printed once each time the user selects a radio button.






Listener listener = new Listener() {

    public void handleEvent(Event event) {

        Button button = (Button) event.widget;

        if (!button.getSelection()) return;

        System.out.println(

"Arriving " + button.getText());

    }

};

Button land = new Button(shell, SWT.RADIO);

land.setText("By Land");

land.addListener(SWT.Selection, listener);

Button sea = new Button(shell, SWT.RADIO);

sea.setText("By Sea");

sea.addListener(SWT.Selection, listener);

sea.setSelection(true);


Figure 7.1 shows this code fragment running within Shell.

Figure 7.1. Using SWT.Selection with two radio buttons.

graphics/07fig01.gif


    Previous Section  < Day Day Up >  Next Section