Java programming course: 18.3 Creating a toolbar


Creating a toolbar

Whereas the menu bar provides selectable options for all an application's functions, a toolbar provides a strip consisting typically of icons for the most frequently used facilities. Oracle provides a downloadable set of toolbar icons that you can use in applications from the following URL: 

https://www.oracle.com/java/technologies/java-archive-downloads-java-client-downloads.html#7520-jlf-1.0-oth-JPR

Unzip the downloaded file to extract the file called jlfgr-1_0.jar, which is a Java Archive containing the icons. Now in NetBeans, right click on the VirtualZoo project node and select Properties. In the Categories list on the left select Libraries, and then click the Add JAR/Folder button. Browse to the extracted jlfgr-1_0.jar file and click Open. The dialog should now show the file listed under the Utilities.jar that you added in an earlier section:

Project Properties dialog

Click the OK button. If you now expand the Libraries node in the Projects window you will see the entry for jlfgr-1_0.jar, and you can also expand this file to see its folders and then the icons within these folders.

You should now rebuild the project in order for the icons to be available when you run the application (right-click on the VirtualZoo project node and select Clean and Build).

You will shortly create a toolbar with an icon so the user can invoke the "feeding time" function, but before doing so it is worth considering the fact that the user will then have two separate ways of invoking that function: either through the menu option File | Feeding Time... or by clicking the toolbar icon. Because the action that needs to occur is identical in both cases it makes sense to utilise a single object that both the menu item and the toolbar icon can invoke. Java provides an interface called Action that enables this very facility, so create a new class under virtualzoo.ui called FeedingTimeAction, as follows:

package virtualzoo.ui;

import java.awt.event.*;
import javax.swing.*;

public class FeedingTimeAction extends AbstractAction {
    
    private AdministratorFrame owner;
    
    FeedingTimeAction(AdministratorFrame owner) {
        this.owner = owner;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JDialog d = new FeedingTimeDialog(owner);
        d.setVisible(true);
    }
    
}
 
  • The class extends the Java supplied AbstractAction class (which implements the Action interface). The AbstractAction class provides some useful facilities which you will use shortly
  • The constructor takes a reference to the owning JFrame
  • Because the Action interface itself extends ActionListener you have the familiar actionPerformed() method. Above, it has the same code as is defined in the inner class FeedingTimeListener in ZooMenuBar

The constructor in FeedingTimeAction can be expanded to specify certain characteristics associated with this action, such as its text and icon. Import the java.net package and then add the following code to the constructor:

FeedingTimeAction(AdministratorFrame owner) {
    this.owner = owner;

    // Set the action's name
    putValue(Action.NAME, "Feeding Time...");
        
    // Set the action's hover help (used by toolbar)
    putValue(Action.SHORT_DESCRIPTION, "Feed the animals");
        
    // Set the action's small icon (used by menu bar)
    URL iconUrlSmall = getClass().getResource
            ("/toolbarButtonGraphics/development/Bean16.gif");
    putValue(Action.SMALL_ICON, new ImageIcon(iconUrlSmall));
        
    // Set the action's large icon (used by toolbar)
    URL iconUrlLarge = getClass().getResource
            ("/toolbarButtonGraphics/development/Bean24.gif");
    putValue(Action.LARGE_ICON_KEY, new ImageIcon(iconUrlLarge));
}
 

The AbstractAction class you are inheriting allows you to set various settings using its putValue() method, where the first argument is the setting type and the second argument is the setting value:

  • The Action.NAME setting provides the text that will appear in the menu bar
  • The Action.SHORT_DESCRIPTION setting provides the hover help that appears when the user hovers the mouse over the icon in the toolbar
  • The Action.SMALL_ICON setting provides the small icon to appear alongside the menu bar text
  • The Action.LARGE_ICON_KEY setting provides the large icon to appear in the toolbar

The technique to load an icon image is to firstly create a URL object using the getResource() method of any class, and then use the URL object to create an ImageIcon object. The argument to getResource() is the path inside the jlfgr-1_0.jar file of the icon you require

Because ideally you want the same Action object to be used for both the menu bar and the toolbar you will convert the FeedingTimeAction class to be a singleton.

Change the constructor visibility to private:

Declare a static variable of type FeedingTimeAction to hold a reference to the singleton object:

private FeedingTimeAction(AdministratorFrame owner) { 

Declare a static variable of type FeedingTimeAction to hold a reference to the singleton object:

public class FeedingTimeAction extends AbstractAction {
    
    private static FeedingTimeAction instance;
    
    private AdministratorFrame owner;
    
    private FeedingTimeAction(AdministratorFrame owner) {
 

Define a static method called getInstance() that returns the singleton object, creating it if it is the first time:

public static FeedingTimeAction getInstance(AdministratorFrame owner) {
    if (instance == null) {
        instance = new FeedingTimeAction(owner);
    }
    return instance;
}
 

In ZooMenuBar delete the FileFeedingTimeListener inner class (as it is no longer needed), and then change the instantiation of the fileFeedingTime object to obtain the FeedingTimeAction singleton object rather than directly setting the text and a listener, since the Action object will take care of these things for you:

private void buildFileMenu() {
    fileMenu = new JMenu("File");

    fileFeedingTime =
		new JMenuItem(FeedingTimeAction.getInstance(owner));
    fileMenu.add(fileFeedingTime);

    fileMenu.addSeparator();

    fileExit = new JMenuItem("Exit...");
    fileExit.addActionListener(new FileExitListener());
    fileMenu.add(fileExit);
}
 

If you run the application, you should see that the small icon now appears alongside the menu text for the option.

With the above now in place it is easy to reuse when creating a toolbar. In Java you can make use of the JToolBar class, so in virtualzoo.ui create a new class called ZooToolBar which extends it:

package virtualzoo.ui;

import javax.swing.*;

public class ZooToolBar extends JToolBar {
    
    ZooToolBar(AdministratorFrame owner) {
        add(FeedingTimeAction.getInstance(owner));
    }
    
}
 

In the constructor the add() method adds an Action object to the toolbar. In this case it just gets the FeedingTimeAction singleton object. You can have as many add() calls as you need, and you can use the addSeparator() method to separate them into groups with a vertical bar.

Finally, in the constructor of AdministratorFrame you can add an instance of ZooToolBar to the frame's NORTH position:

// Create toolbar
add(new ZooToolBar(this), BorderLayout.NORTH);
 

The resulting application should look like this:

Toolbar inside frame

Note the large icon in the toolbar, which if you hover the mouse over provides the hover help as defined. The menu option and toolbar option will perform the same action.



Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Monday, 27 October 2025

Captcha Image