• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 4. SWT Toolbars > Making the Buttons Work—Adding Listeners

4.4. Making the Buttons Work—Adding Listeners

As with menus (and, in fact, all widgets), you must now add a listener for each button and code the widgetSelected() method for each SelectionListener to take the appropriate action.

4.4.1. How do I do that?

The Listener code for the four toolbar buttons created by Example 4-1 is shown here:

openToolItem.addSelectionListener(new SelectionListener( ) {
      public void widgetSelected(SelectionEvent event) {
          System.out.println("Open");                    
      }
      public void widgetDefaultSelected(SelectionEvent event)
      {                    
      }
});
            
saveToolItem.addSelectionListener(new SelectionListener( ) {
      public void widgetSelected(SelectionEvent event) {
          System.out.println("Save");                    
      }
      public void widgetDefaultSelected(SelectionEvent event)
      {                    
      }
});
            
cutToolItem.addSelectionListener(new SelectionListener( ) {
      public void widgetSelected(SelectionEvent event) {
          System.out.println("Cut");                    
      }
      public void widgetDefaultSelected(SelectionEvent event)
      {                    
      }
});
            
copyToolItem.addSelectionListener(new SelectionListener( ) {
      public void widgetSelected(SelectionEvent event) {
          System.out.println("Copy");                    
      }
      public void widgetDefaultSelected(SelectionEvent event)
      {                    
      }
});
            
pasteToolItem.addSelectionListener(new SelectionListener( ) {
      public void widgetSelected(SelectionEvent event) {
          System.out.println("Paste");                    
      }
      public void widgetDefaultSelected(SelectionEvent event)
      {                    
      }
});

					  

Adding the preceding code to the constructor for ToolbarShellExample results in the toolbar buttons becoming functional—at least to the point of printing a message to the Console when they are pressed, as shown in Figure 4-2.

Figure 4-2. The Eclipse Console


4.4.2. What about...

all that duplicate code in the SelectionListener classes? One of the goals of object-oriented programming is to reduce the amount of code that is duplicated in an application, yet as you see, the widgetSelected( ) code added to the ToolItem objects is identical to that added to the MenuItem objects created in Example 4-1.

This can be corrected by creating named inner classes that implement the SelectionListener interface, as shown in Example 4-2.

Example 4-2. Using named inner classes for SelectionListeners

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.*;

public class ToolbarShellExample {    
        Display d;
        Shell s;
        ToolbarShellExample( )    {
            d = new Display( );
            s = new Shell(d);
            s.setSize(300,300);
            s.setImage(new Image(d, "c:\\icons\\JavaCup.ico"));
            s.setText("A Shell Toolbar Example");
            
            final ToolBar bar = new ToolBar(s,SWT.HORIZONTAL);
            bar.setSize(500,70);
            bar.setLocation(0,0);
            // create images for toolbar buttons
            final Image saveIcon = new Image(d, "c:\\icons\\save.jpg");
            final Image openIcon = new Image(d, "c:\\icons\\open.jpg");
            final Image childIcon = new Image(d, "c:\\icons\\userH.ico");
            final Image cutIcon = new Image(d, "c:\\icons\\cut.jpg");
            final Image copyIcon = new Image(d, "c:\\icons\\copy.jpg");
            final Image pasteIcon = new Image(d, "c:\\icons\\paste.jpg");
            // create and add the button for performing an open operation
            final ToolItem openToolItem = new ToolItem(bar, SWT.PUSH);
            openToolItem.setImage(openIcon);
            openToolItem.setText("Open");
            openToolItem.setToolTipText("Open File");
            
            //create and add the button for performing a save operation
            final ToolItem saveToolItem = new ToolItem(bar, SWT.PUSH);
            saveToolItem.setImage(saveIcon);
            saveToolItem.setText("Save");
            saveToolItem.setToolTipText("Save File");
            
            final ToolItem sep1 = new ToolItem(bar, SWT.SEPARATOR);
            
            //create and add the button for performing a cut operation
            final ToolItem cutToolItem = new ToolItem(bar, SWT.PUSH);
            cutToolItem.setImage(cutIcon);
            cutToolItem.setText("Cut");
            cutToolItem.setToolTipText("Cut");
            
            // create and add the button for performing a copy operation
            final ToolItem copyToolItem = new ToolItem(bar, SWT.PUSH);
            copyToolItem.setImage(copyIcon);
            copyToolItem.setText("Copy");
            copyToolItem.setToolTipText("Copy");
            
            // create and add the button for performing a paste operation
            final ToolItem pasteToolItem = new ToolItem(bar, SWT.PUSH);
            pasteToolItem.setImage(pasteIcon);
            pasteToolItem.setText("Paste");
            pasteToolItem.setToolTipText("Paste");
            
            // create inner classes for SelectionListeners            
            class Open implements SelectionListener
            {
                public void widgetSelected(SelectionEvent event) {
                    System.out.println("Open");                    
                }
                public void widgetDefaultSelected(SelectionEvent event)
                {                    
                }
            }
            
            class Save implements SelectionListener
            {
                public void widgetSelected(SelectionEvent event) {
                    System.out.println("Save");                    
                }
                public void widgetDefaultSelected(SelectionEvent event)
                {                    
                }
            }
            
            class Cut implements SelectionListener
            {
                public void widgetSelected(SelectionEvent event) {
                    System.out.println("Cut");                    
                }
                public void widgetDefaultSelected(SelectionEvent event)
                {                    
                }
            }
            
            class Copy implements SelectionListener
            {
                public void widgetSelected(SelectionEvent event) {
                    System.out.println("Copy");                    
                }
                public void widgetDefaultSelected(SelectionEvent event)
                {                    
                }
            }
            
            class Paste implements SelectionListener
            {
                public void widgetSelected(SelectionEvent event) {
                    System.out.println("Paste");                    
                }
                public void widgetDefaultSelected(SelectionEvent event)
                {                    
                }
            }
            
            openToolItem.addSelectionListener(new Open( ));            
            saveToolItem.addSelectionListener(new Save( ));            
            cutToolItem.addSelectionListener(new Cut( ));            
            copyToolItem.addSelectionListener(new Copy( ));            
            pasteToolItem.addSelectionListener(new Paste( ));            
            
            // create the menu system
            Menu m = new Menu(s,SWT.BAR);
            // create a File menu and add an Exit item
            final MenuItem file = new MenuItem(m, SWT.CASCADE);
            file.setText("&File");
            final Menu filemenu = new Menu(s, SWT.DROP_DOWN);
            file.setMenu(filemenu);
            final MenuItem openMenuItem = new MenuItem(filemenu, SWT.PUSH);
            openMenuItem.setText("&Open\tCTRL+O");
            openMenuItem.setAccelerator(SWT.CTRL+'O');
            final MenuItem saveMenuItem = new MenuItem(filemenu, SWT.PUSH);
            saveMenuItem.setText("&Save\tCTRL+S");
            saveMenuItem.setAccelerator(SWT.CTRL+'S');
            final MenuItem separator = new MenuItem(filemenu, SWT.SEPARATOR);
            final MenuItem exitMenuItem = new MenuItem(filemenu, SWT.PUSH);
            exitMenuItem.setText("E&xit");
            
            // create an Edit menu and add Cut, Copy, and Paste items
            final MenuItem edit = new MenuItem(m, SWT.CASCADE);
            edit.setText("&Edit");
            final Menu editmenu = new Menu(s, SWT.DROP_DOWN);
            edit.setMenu(editmenu);
            final MenuItem cutMenuItem = new MenuItem(editmenu, SWT.PUSH);
            cutMenuItem.setText("&Cut");
            final MenuItem copyMenuItem = new MenuItem(editmenu, SWT.PUSH);
            copyMenuItem.setText("Co&py");
            final MenuItem pasteMenuItem = new MenuItem(editmenu, SWT.PUSH);
            pasteMenuItem.setText("&Paste");
            
            //create a Window menu and add Child items
            final MenuItem window = new MenuItem(m, SWT.CASCADE);
            window.setText("&Window");
            final Menu windowmenu = new Menu(s, SWT.DROP_DOWN);
            window.setMenu(windowmenu);
            final MenuItem maxMenuItem = new MenuItem(windowmenu, SWT.PUSH);
            maxMenuItem.setText("Ma&ximize");
            final MenuItem minMenuItem = new MenuItem(windowmenu, SWT.PUSH);
            minMenuItem.setText("Mi&nimize");
            
            // create a Help menu and add an About item
            final MenuItem help = new MenuItem(m, SWT.CASCADE);
            help.setText("&Help");
            final Menu helpmenu = new Menu(s, SWT.DROP_DOWN);
            help.setMenu(helpmenu);
            final MenuItem aboutMenuItem = new MenuItem(helpmenu, SWT.PUSH);
            aboutMenuItem.setText("&About");    
            
            // add action listeners for the menu items
            
            openMenuItem.addSelectionListener(new Open( ));             
            saveMenuItem.addSelectionListener(new Save( ));             
            exitMenuItem.addSelectionListener(new SelectionListener( ) {
                public void widgetSelected(SelectionEvent e) {
                    System.exit(0);
                }
                public void widgetDefaultSelected(SelectionEvent e)
                {                    
                }
            });            
            cutMenuItem.addSelectionListener(new Cut( ));             
            copyMenuItem.addSelectionListener(new Copy( ));             
            pasteMenuItem.addSelectionListener(new Paste( ));             
            maxMenuItem.addSelectionListener(new SelectionListener( ) {
                public void widgetSelected(SelectionEvent e) {
                    Shell parent = (Shell)maxMenuItem.getParent( ).getParent( );
                    parent.setMaximized(true);
                }
                public void widgetDefaultSelected(SelectionEvent e)
                {                    
                }
            });
            
            minMenuItem.addSelectionListener(new SelectionListener( ) {
                public void widgetSelected(SelectionEvent e) {
                    Shell parent = (Shell)minMenuItem.getParent( ).getParent( );
                    parent.setMaximized(false);
                }
                public void widgetDefaultSelected(SelectionEvent e)
                {                    
                }
            });
            
            aboutMenuItem.addSelectionListener(new SelectionListener( ) {
                public void widgetSelected(SelectionEvent e) {
                    System.out.println("Help Invoked");
                }
                public void widgetDefaultSelected(SelectionEvent e)
                {                    
                }
            }); 
            
            s.setMenuBar(m);        
            s.open( );
            while(!s.isDisposed( )){
                if(!d.readAndDispatch( ))
                    d.sleep( );
            }
            d.dispose( );
        }        
}

					  

4.4.3. What just happened?

As you can see from Example 4-2, the number of duplicated lines is decreased. This is accomplished by adding a named inner class for each SelectionListener that was shared between a menu item and a toolbar button. For example, the inner class for the Open functionality is now written as follows:


Note:

This saves a little code—how much depends on the contents of the inner classes. Remember, he who writes the fewest lines wins.


class Open implements SelectionListener
{
    public void widgetSelected(SelectionEvent event) {
          System.out.println("Open");                    
    }
    public void widgetDefaultSelected(SelectionEvent event)
   {                    
   }
}

The inner class is then used for both the menu item and the toolbar button by calling the addSelectionListener() method for each:

openToolItem.addSelectionListener(new Open( ));
openMenuItem.addSelectionListener(new Open( ));

Either approach is valid: choose whichever best matches your coding philosophy.

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint