Inside XML (Inside (New Riders))

     

9.5.1 Problem

You want to catch toolbar click events.

9.5.2 Solution

Add a listener to the toolbar buttons . Just create a new Listener object, and use the toolbar button's addListener method to add that listener.

9.5.3 Discussion

To complete the example discussed in the two previous recipes, create a new listener of the Listener class to handle the buttons, handle click events by displaying the caption of the clicked button (which you can get from the tool item's getText method), and add the new listener to the toolbar buttons. You can see how that works in Example 9-2.

Example 9-2. Creating toolbars

package org.cookbook.ch09; import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; public class ToolbarClass { public static void main(String [] args) { Display display = new Display( ); final Shell shell = new Shell(display); shell.setSize(300, 200); shell.setText("Toolbar Example"); ToolBar toolbar = new ToolBar(shell, SWT.NONE); toolbar.setBounds(0, 0, 200, 70); ToolItem toolItem1 = new ToolItem(toolbar, SWT.PUSH); toolItem1.setText("Save"); ToolItem toolItem2 = new ToolItem(toolbar, SWT.PUSH); toolItem2.setText("Save As"); ToolItem toolItem3 = new ToolItem(toolbar, SWT.PUSH); toolItem3.setText("Print"); ToolItem toolItem4 = new ToolItem(toolbar, SWT.PUSH); toolItem4.setText("Run"); ToolItem toolItem5 = new ToolItem(toolbar, SWT.PUSH); toolItem5.setText("Help"); final Text text = new Text(shell, SWT.BORDER); text.setBounds(55, 80, 200, 25); Listener toolbarListener = new Listener( ) { public void handleEvent(Event event) { ToolItem toolItem =(ToolItem)event.widget; String caption = toolItem.getText( ); text.setText("You clicked " + caption); } }; toolItem1.addListener(SWT.Selection, toolbarListener); toolItem2.addListener(SWT.Selection, toolbarListener); toolItem3.addListener(SWT.Selection, toolbarListener); toolItem4.addListener(SWT.Selection, toolbarListener); toolItem5.addListener(SWT.Selection, toolbarListener); shell.open( ); while (!shell.isDisposed( )) { if (!display.readAndDispatch( )) display.sleep( ); } display.dispose( ); } }

The results appear in Figure 9-4; the toolbar appears at upper left (you can position it where you want using setBounds or using an SWT layout). When the user clicks a button, the code reports his selections, as shown in Figure 9-4.

Figure 9-4. Using a toolbar

9.5.4 See Also

Recipe 9.3 on creating toolbars; Recipe 9.4 on embedding buttons in toolbars; Recipe 9.6 on embedding combo boxes, text widgets, and menus in toolbars; Chapter 8 in Eclipse (O'Reilly).

Категории