Swing Solutions: Integrating Menus in JWord
- Swing Solutions: Integrating Menus in JWord
- What's Next?
- Books by Steve Haines:
Swing Solutions: Integrating Menus in JWord
By Steve Haines - September 20, 2000
Welcome to the third article in the Swing Solutions' JWord series. The last two articles introduced you to and provided you with an implementation of the Java Swing support for creating menus. This article discusses the Swing classes that used for creating toolbars.
Swing Toolbars
If you have ever used a computer, you have certainly been exposed to the toolbar. A toolbar is a collection of buttons that invoke programmatic actions which are typically available through a menu selection. An example of some toolbar buttons with which you should be familiar include the Back, Forward, Stop, and Refresh buttons; you should see these buttons in the web browser that you are using to view this page. The toolbar consists of the region that encompasses the toolbar buttons, as well as the buttons themselves.
Figure 1 is an example of the toolbar that we are going to develop in the next two articles.
Figure 1 JWord with its Toolbar
A toolbar is not limited to the top of your window; it can also be docked to any of the four sides of your window (see figures 2, 3, and 4), or it may float (see figure 5).
Figure 2 JWord with its Toolbar docked on the left side
Figure 3 JWord with its Toolbar docked on the bottom
Figure 4 JWord with its Toolbar docked on the right side
Figure 5 JWord with its Toolbar floating
JButton
Each individual button within the toolbar is an instance of the JButton class. A JButton instance can have a text field and/or an icon, and can display floating tooltips; JButton instances that are typically used in the context of a toolbar do not make use of the text element. Its constructors are shown in Table 1.
Table 1. JButton Constructors
Constructor |
Description |
JButton() |
Creates a button without set text or icon |
JButton(Action a) |
Creates a button where properties are taken from the Action supplied |
JButton(Icon icon) |
Creates a button with an icon |
JButton(String text) |
Creates a button with text |
JButton(String text, Icon icon) |
Creates a button with initial text and an icon |
Most of these constructors are fairly self-explanatory; they accept either text or an icon, both text and an icon, or neither. The one that accepts an Action argument requires some explanation. The Action interface is a new addition to the Java 2 Standard Edition version 1.3; it offers great functionality to Java developers by providing a central repository for (1) object text, (2) object icons, (3) enabled/disabled states, and (as its name implies) (4) actions. This article addresses the traditional approach to handling action events, but an upcoming article will address the new 1.3 way to handle action events . If you are curious in the meantime, take a look at the Java SDK documentation under Action and AbstractAction.
When building toolbar buttons, our goal is to construct buttons without text. Following are a couple of sample JButton instances:
// Create a JButton from an image file as an ImageIcon JButton fileOpen = new JButton( new ImageIcon( images/fileopen.gif ) ); // Create a JButton from a Java Look and Feel Graphics Repository icon JButton fileNew = new JButton( getImage( "general/New24.gif" ) );
Recall that in the last article,we defined a method getImage(), which loads an image from a set of common images that are released by Sun and are known as the Java Look And Feel Graphics Repository (see http://developer.java.sun.com/developer/techDocs/hi/repository/ for more information.) To save you from referencing that article, below is the code for the getImage() method:
public ImageIcon getImage( String strFilename ) { // Get an instance of our class Class thisClass = getClass(); // Locate the desired image file and create a URL to it java.net.URL url = thisClass.getResource( "toolbarButtonGraphics/" + strFilename ); // See if we successfully found the image if( url == null ) { System.out.println( "Unable to load the following image: " + strFilename ); return null; } // Get a Toolkit object Toolkit toolkit = Toolkit.getDefaultToolkit(); // Create a new image from the image URL Image image = toolkit.getImage( url ); // Build a new ImageIcon from this and return it to the caller return new ImageIcon( image ); }
For a complete explanation of this code, please refer back to the article: Swing Solutions: Integrating Menus in JWord.
JToolBar
Once we have defined a set of JButton objects, we need a container that will hold them. The JToolBar class provides such a container; as previously mentioned , the JToolBar class can be docked to one of the four sides of your JFrame, or it can float. Table 2 shows the constructors for the JToolBar class.
Table 2. JToolBar Constructors
Constructor |
Description |
JToolBar() |
Creates a new toolbar; orientation defaults to HORIZONTAL |
JToolBar(int orientation) |
Creates a new toolbar with the specified orientation |
JToolBar(String name) |
Creates a new toolbar with the specified name |
JToolBar(String name, int orientation) |
Creates a new toolbar with a specified name and orientation |
When creating a JToolBar, you can specify the toolbars orientation (either HORIZONTAL or VERTICAL) and the name of the toolbar, which is displayed when the toolbar is floating (see figure 5). The following code constructs three toolbars using the aforementioned constructors:
JToolBar toolbar = new JToolBar( My Toolbar ); JToolBar toolbar2 = new JToolBar( JToolBar.VERTICAL ); JToolBar toolbar3 = new JToolBar( My Toolbar, JToolBar.VERTICAL );
If you look closely at the JToolBar documentationand even if you look at its source codeyou may be puzzled that the orientation constants HORIZONTAL and VERTICAL are not defined. The JToolBar class implements an interface named SwingConstants, which defines a set of constants that are used by the various Swing components. By implementing this interface, the JToolBar class inherits the definitions of both VERTICAL and HORIZONTAL.
Table 3 shows some of the more commonly used JToolBar methods.
Table 3. JToolBar Methods
Method |
Description |
JButton add(Action a) |
Adds a new JButton that dispatches the action |
Component add(Component comp) |
Adds the specified component to the end of this container (inherited from Container) |
void addSeparator() |
Appends a toolbar separator of default size to the end of the toolbar |
void addSeparator(Dimension size) |
Appends a toolbar separator of a specified size to the end of the toolbar |
boolean isFloatable() |
Returns true if the JToolBar can be dragged out by the user |
void setFloatable(boolean b) |
Sets whether the toolbar can be made to float |
int getOrientation() |
Returns the current orientation of the toolbar |
void setOrientation(int o) |
Sets the orientation of the toolbar |
Insets getMargin() |
Returns the margin between the toolbar's border and its buttons |
void setMargin(Insets m) |
Sets the margin between the toolbar's border and its buttons |
The add() methods (table 3) show both the tradional way to add buttons (Component instances), as well as the new Java 2 SDK version 1.3 method of adding buttons (Action instances). There are two methods you may use in order to add separators between button groups named addSeparator() (see figure 1, 2, 3, 4, or 5, and look at the space between the print icon and the cut icon).
JToolBar objects can be made floatable by calling the setFloatable() method, and their floatable state can be verified by calling the isFloatable() method (by default, the JToolBar class is floatable.) The JToolBar objects orientation can be verified and updated through the getOrientation() and setOrientation() methods. Finally, the getInsets() and setInsets() methods allow you to retrieve and specify the margins between the toolbars border and its buttons.
The following code demonstrates how to create a few JButton objects, a JToolBar object, and how to build the a complete toolbar:
// Create some JButton objects JButton fileOpen = new JButton( getImage( general/New24.gif ) ); JButton fileSave = new JButton( getImage( general/Save24.gif ) ); JButton editCut = new JButton( getImage( general/Cut24.gif ) ); JButton editCopy = new JButton( getImage( general/Copy24.gif ) ); // Create the JToolBar JToolBar toolbar = new JToolBar( My Toolbar ); // Add the buttons to the JToolBar toolbar.add( fileOpen ); toolbar.add( fileSave ); toolbar.addSeparator(); toolbar.add( editCut ); toolbar.add( editCopy );
Events
A toolbar, like a menu, handles events through its elements: JButton objects. The JButton class method addActionListener() accepts a class that implements the ActionListener interface. It is prototyped as follows:
public void addActionListener(ActionListener l)
When a JButton is clicked, the ActionListener implementing classs actionPerformed( ActionEvent e ) method will be called with an ActionEvent that refers to the JButton which generated the event. The following code segment shows a sample event handler for a JToolBars JButton:
public class MyClass implements ActionListener { JButton button1 = new JButton( images/myimage1.gif ); JButton button2 = new JButton( images/myimage2.gif ); JToolBar toolbar = new JToolBar( My Toolbar ); public MyClass() { // Add MyClass as an ActionListener to the JButtons button1.addActionListener( this ); button2.addActionListener( this ); // Add the buttons to the toolbar toolbar.add( button1 ); toolbar.add( button2 ); } /** * Handle the toolbar button events */ public void actionPerformed(ActionEvent e) { if( e.getSource() == button1 ) { System.out.println( Button 1 Pressed ); } else if( e.getSource() == button2 ) { System.out.println( Button 2 Pressed ); } } }
Where does the toolbar go?
Were almost done for this installment, but one more very important thing is left for our discussion: now that you have this beautiful toolbar, what do you do with it!?
The best way to handle toolbarsactually, the only way to handle toolbarsif you want the docking functionality discussed earlier, is to create a container (usually JFrame in applications) whose layout manager is a BorderLayout and does not have any children on its four sides. The JToolBar can then be added to the container at any of the four sides by the standard content pane add() method:
public class MyClass extends JFrame implements ActionListener { ... public MyClass() { ... // Set the layout manager for the JFrames content pane to a new BorderLayout getContentPane().setLayoutManager( new BorderLayout() ); // Add the toolbar to the top (NORTH) of content pane getContentPane().add( toolbar, BorderLayout.NORTH ); } ... }