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

Chapter 4. SWT Toolbars > Creating Toolbar Buttons

4.2. Creating Toolbar Buttons

The next step in creating a toolbar is to add the buttons. You need one button for each function you wish to enable the user to access from the toolbar. Buttons can have assigned to them either images or labels, or both, to aid the user in understanding exactly what function the button triggers.


Most toolbar buttons make use of assigned images rather than text labels.

Either way, you create toolbar buttons by creating instances of the ToolItem class—one for each button.


There are some standards that govern what images to use for specific functions. A scissors image is used for cut, for example, while a disk image is used for save. A great way to determine what images to use is to study other applications running on your target platforms.

4.2.1. How do I do that?

The ToolItem class constructor accepts as arguments a reference to the containing ToolBar, and the style of the button you wish to create. There are five styles you can use when creating ToolItem buttons:


Creates a clickable toolbar button.


Creates a toolbar button that toggles between selected and deselected.


Creates a toolbar button that is part of a group of buttons in which only one button can be selected.


Adds spacing between toolbar buttons.


Creates a toolbar button to which a drop-down menu can be attached.

The code needed to create a text-only button is simple:

final ToolItem textItem = new ToolItem(bar, SWT.PUSH);
textItem.setText("Open Child");

Adding an image to a ToolItem is very similar to adding text, except that you use the setImage( ) method rather than the setText( ) method. First, you must create an instance of the Image class to load up the picture; then you associate that image with the ToolItem:

Image icon = new Image(d, "c:\\icons\\JavaCup.ico");
final ToolItem imageItem = new ToolItem(bar, SWT.PUSH);

Creating ToolItem buttons that use both images and text is simply a matter of calling both the setImage( ) and setText( ) methods:

Image icon = new Image(d, "c:\\icons\\JavaCup.ico");
final ToolItem textImageItem = new ToolItem(bar, SWT.PUSH);
textImageItem.setText("Java Icon");

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