Easy to Learn Java: Programming Articles, Examples and Tips

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

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

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

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 
2.
Basic text editor: part I - menus 
3.
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");

    mFile.setMnemonic('f');

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

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

      public void actionPerformed(ActionEvent e) {

        m_monitor.setText("");

      }

    };

    JMenuItem item =  mFile.add(actionNew); 

    item.setMnemonic('n');

    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); 

    item.setMnemonic('o');

    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); 

    item.setMnemonic('s');

    mFile.addSeparator();

    Action actionExit = new AbstractAction("Exit") {

      public void actionPerformed(ActionEvent e) {

        System.exit(0);

      }

    };

    item =  mFile.add(actionExit); 

    item.setMnemonic('x');

    menuBar.add(mFile);

    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) ]


Search Books
Custom Search
Latest articles
 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

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


[ 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