Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures


Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips


Submit News
Search the site here...

Swing Chapter 12 (The basics) Menus, Toolbars, and Actions. Easy for reading, Click here!

Custom Search
Swing Chapter 12 (The basics) Menus, Toolbars, and Actions. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 3/5 

Previous Page Previous Page (2/5) - Next Page (4/5) Next Page
Subpages: 1. JMenus, Toolbars, and Actions overview 
Basic text editor: part I - menus 
Basic text editor: part II - Toolbars and Actions 
4. Basic text editor: part III - Custom toolbar components 
5. Basic text editor: part IV- Custom menu components 

12.3  Basic text editor: part II - toolbars and actions

Swing provides the Action interface to simplify the creation of menu items. As we know, implementations of this interface encapsulate both knowledge of what to do when a menu item or toolbar button is selected (by extending the ActionListener interface) and knowledge of how to render the component itself (by holding a collection of bound properties such as NAME, SMALL_ICON, etc.). We can create both a menu item and a toolbar button from a single Action instance, conserving code and providing a reliable means of ensuring consistency between menus and toolbars.

The following example uses the AbstractAction class to add a toolbar to our BasicTextEditor application. By converting the ActionListeners used in the example above to AbstractActions, we can use these actions to create both toolbar buttons and menu items with very little additional work.

Figure 12.3 Process of un-docking, dragging, and docking a floating JToolBar.

<<file figure12-3.gif>>

Figure 12.4 A floating JToolBar placed in a non-dockable region.

<<file figure12-4.gif>>

The Code: BasicTextEditor.java

see \Chapter12\2

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.util.*;

import javax.swing.*;

import javax.swing.event.*;

public class BasicTextEditor extends JFrame


  // Unchanged code from section 12.2

  protected JToolBar m_toolBar;

  protected JMenuBar createMenuBar() {

    final JMenuBar menuBar = new JMenuBar();

    JMenu mFile = new JMenu("File");


    ImageIcon iconNew = new ImageIcon("file_new.gif");

    Action actionNew = new AbstractAction("New", iconNew) {

      public void actionPerformed(ActionEvent e) {




    JMenuItem item =  mFile.add(actionNew); 


    ImageIcon iconOpen = new ImageIcon("file_open.gif");

    Action actionOpen = new AbstractAction("Open...", iconOpen) {

      public void actionPerformed(ActionEvent e) {

        // Unchanged code from section 12.2



    item =  mFile.add(actionOpen); 


    ImageIcon iconSave = new ImageIcon("file_save.gif");

    Action actionSave = new AbstractAction("Save...", iconSave) {

      public void actionPerformed(ActionEvent e) {

        // Unchanged code from section 12.2



    item =  mFile.add(actionSave); 



    Action actionExit = new AbstractAction("Exit") {

      public void actionPerformed(ActionEvent e) {




    item =  mFile.add(actionExit); 



    m_toolBar = new JToolBar();

    JButton btn1 = m_toolBar.add(actionNew);

    btn1.setToolTipText("New text");

    JButton btn2 = m_toolBar.add(actionOpen);

    btn2.setToolTipText("Open text file");

    JButton btn3 = m_toolBar.add(actionSave);

    btn3.setToolTipText("Save text file");

    // Unchanged code from section 12.2

    getContentPane().add(m_toolBar, BorderLayout.NORTH);

    return menuBar;


  // Unchanged code from section 12.2


Understanding the Code

Class BasicTextEditor

This class now declares one more instance variable, JToolBar m_toolBar. The constructor remains unchanged and is not listed here. The createMenuBar() method now creates AbstractAction instances instead of ActionListeners. These objects encapsulate the same action handling code we defined in the last example, as well as the text and icon to display in associated menu items and toolbar buttons. This allows us to create JMenuItems using the JMenu.add(Action a) method, and JButtons using the JToolBar.add(Action a) method. These methods return instances that we can treat as any other button component and do things such as set the background color assign a different text alignment.

Our JToolBar component is placed in the NORTH region of our content pane, and we make sure to leave the EAST, WEST, and SOUTH regions empty allowing it to dock on all sides.

Running the Code

Verify that the toolbar buttons work as expected by opening and saving a text file. Try dragging the toolbar from its 'handle' and note how it is represented by an empty gray window as it is dragged. The border will change to a dark color when the window is in a location where it will dock if the mouse is released. If the border does not appear dark, releasing the mouse will result in the toolbar being placed in its own JFrame. Figure 12.3 illustrates the simple process of undocking, dragging, and docking our toolbar in a new location. Figure 12.4 shows our toolbar in its own JFrame when undocked and released outside of a dockable region (also referred to as a hotspot).

Note: The current JToolBar implementation does not easily allow the use of multiple floating toolbars as is common in many modern applications. We hope to see more of this functionality built into future versions of Swing.

UI Guideline : Vertical or Horizontal?

In some applications, you may prefer to leave the selection of a vertical or horizontal toolbar to the user. More often than not, you as designer can make that choice for them. Consider whether vertical or horizontal space is more valuable for what you need to display. If, for example, you are displaying Letter text then you probably need vertical space more than horizontal space. Usually in PC applications, vertical space is at a premium.

When vertical space is at a premium, place the toolbar vertically thus freeing up valuable vertical space.
When horizontal space is at a premium, place the toolbar horizontally thus freeing up valuable horizontal space.

Almost never allow a floating toolbar, as it has a tendency to get lost under other windows. Floating toolbars are for advanced users who understand the full operation of the computer system. Consider the technical level of your user group before making the design choice for a floating toolbar.

[ Return to Swing (Book) ]

Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color

[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3

[ More in News Section ]

Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy