Click here to close now.

Welcome!

Java Authors: AppDynamics Blog, Kelly Murphy, Pat Romanski, Liz McMillan, Elizabeth White

Related Topics: Java

Java: Article

How To Build a Toolbar From a Menu

For better usability, versatility, and user friendliness

As users of software applications, we commonly deal with the Graphical User Interface, which, in most of cases, contains the following main elements:

  1. A menubar, which includes all the available commands and options (we'll call them functionalities)
  2. A toolbar, which is a container for a subset of the most common and useful functionalities (typically a subset of "shortcuts" for the above mentioned commands and options)
  3. A working space that is a kind of "container" panel, where the user can type, draw, or do any-thing related to the application
In this article I'll discuss the relationship between the menu and the toolbar from both sides: the application user and the application programmer.

In the role of developer of an application, I have to design a complete and efficient Graphical User Interface for the application function calls; a common choice is to provide the application with both a menubar and a toolbar.

First I'll start to design the menubar and then provide the GUI with a toolbar; however, I realize that part of the toolbar work was already done at the menubar design time. My question is: Can I save development time and work programming the GUI toolbar by using what it is already done for the menubar?

For example, suppose my text editor-like application supports clipboard operations. I have to insert the menu items "cut," "copy," and "paste" into the "Edit" menu, providing icon, accelerator key, and tooltips text for each of them. Then I have to associate what is commonly called "action," that is the code that implements the functionality (for "cut" it could be to delete the selected text and put it in the clipboard). Finally I have to manage the enabled or disabled status of each item (for example, disabling paste if clipboard is empty and enabling cut and copy if some text is selected). Of course, all these things are required for a complete and useful, user-friendly and good-looking menu.

Actually I would like to do something more, for instance, providing a toolbar for my application. First, I add three buttons with the same cut, copy, and paste icons (no text for them, according to the Look-and-Feel Design Guidelines), specifying the same tooltip text used for the menu items (note that I do exactly what I did before for the menubar). Then I link the buttons to the code that implements their functionalities (I repeat my actions again). At the end I write the code to disable and enable the buttons, following the same criteria used for the menu items. In conclusion, I do the same things twice! And everybody knows that doing something twice is not a matter of laziness; this may easily introduce unexpected errors and cause undesired effects (such as a menu item disabled and the corresponding button enabled), especially when the application grows up and new commands or options are added.

I concluded that my efforts could be better employed in designing and coding a good menubar, leaving the development of the corresponding toolbar to some automatic procedure.

This kind of utility can be very useful for applications that have many functionalities and require frequent maintenance. To my knowledge, even sophisticated GUI design editors (like form editors included in the most common IDEs such as Eclipse or NetBeans) don't offer enough support for this aspect and they don't provide anything that keeps linked menu items and buttons.

Solution
The idea for solving this problem comes from the Action class (which is included in the java.swing package); this class offers an interface that extends the ActionListener and can be used in cases where the same functionality could be accessed by several controls (just like menu items and buttons).

The Action interface allows you to define, in a single place:

  • The actionPerformed method defined by the ActionListener interface. This method is called when the user activates the control (for example, when he or she selects a menu item or presses a button). This method contains the code to implement the functionality.
  • The text describing each functionality; these strings can be used to set the text in a menu item or to display the flyover text for a button or a menu item (tooltip text).
  • The icon that depicts the functionality.
  • The enabled/disabled state of the functionality.
  • The accelerator key used to quickly access the functionality.
  • The mnemonic key used to "navigate" by keyboard through a set of Actions.
Certain containers, including menus and toolbars, know how to manage an Action object. In detail they can achieve information from the Action to:
  • Create the component appropriate for the container (a button for the tool bar, a menu item for the menu)
  • Get the suitable information to render the container (texts, icons, enabled/disabled state)
  • Notify the change of state
  • Activate the functionality
Implementation and Use
JToolBarMenu is an extension of the JToolBar from the javax.swing package (see sample use in Figures 1 and 2). It is initialized with a JMenuBar object, that is, the menubar the toolbar refers to.

There is no limitation on the way the menubar can be built: JToolBarMenu always shows a rational set of buttons derived from the menubar structure. Of course, if the menubar is built in a chaotic form, JToolBarMenu will be not so intuitive and tidy.

The set of buttons showed in the JToolBarMenu follows the same tree structure as the menubar. In fact, as root, there is a menubar, which has attached some menus (primary branches), and each of these branches contains next menu items (leaves) and/or some other submenu (other branches) and recursively going on.

It was developed as an algorithm to arrange, under all possible conditions and in the proper way, any input menubar. This algorithm consists of the following steps:

1.  It scans all menus present in the menubar. For each menu that is not empty, a separator is added to the toolbar.

2.  For each item present in the menu:

  • If the item is a separator, a separator is obviously added.
  • If the item is a submenu, the algorithm is recursively applied to the item again.
  • if the item is a JRadioButtonMenuItem (a menu item with exclusive selection), it's collected in a vector until there is no more contiguous JRadioButtonMenuItems. When the collection is ready, a set of JToggleButton, each one corresponding to the item in the vector, is added and preceded by a new separator.
  • If the item is a JCheckBox-MenuItem (menu item without an exclusive selection), a JToggleButton is added.
  • Otherwise the item is simply a JMenuItem, thus a JButton is added.
This mechanism ensures consistency with the menubar structure and an attractive display because the role of the separators, which are always put in a right and rational position, result in a user-friendly layout.

More Stories By Mauro Micalizzi

Mauro Micalizzi, a researcher, has been involved in software developing for 25 years, and the Java language for seven. He is currently working on GUI, signal processing, and printing framework. Mauro has a degree in computer science.

Comments (2) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Java Developer's Journal News Desk 11/10/05 12:45:57 PM EST

Java Developer's Journal Feature: Building a Toolbar From a Menu. Actually I would like to do something more, for instance, providing a toolbar for my application. First, I add three buttons with the same cut, copy, and paste icons (no text for them, according to the Look-and-Feel Design Guidelines), specifying the same tooltip text used for the menu items (note that I do exactly what I did before for the menubar). Then I link the buttons to the code that implements their functionalities (I repeat my actions again). At the end I write the code to disable and enable the buttons, following the same criteria used for the menu items.

JDJ News Desk 11/10/05 12:20:13 PM EST

Java Developer's Journal Feature: Building a Toolbar From a Menu. Actually I would like to do something more, for instance, providing a toolbar for my application. First, I add three buttons with the same cut, copy, and paste icons (no text for them, according to the Look-and-Feel Design Guidelines), specifying the same tooltip text used for the menu items (note that I do exactly what I did before for the menubar). Then I link the buttons to the code that implements their functionalities (I repeat my actions again). At the end I write the code to disable and enable the buttons, following the same criteria used for the menu items.

@ThingsExpo Stories
The true value of the Internet of Things (IoT) lies not just in the data, but through the services that protect the data, perform the analysis and present findings in a usable way. With many IoT elements rooted in traditional IT components, Big Data and IoT isn’t just a play for enterprise. In fact, the IoT presents SMBs with the prospect of launching entirely new activities and exploring innovative areas. CompTIA research identifies several areas where IoT is expected to have the greatest impact.
Every day we read jaw-dropping stats on the explosion of data. We allocate significant resources to harness and better understand it. We build businesses around it. But we’ve only just begun. For big payoffs in Big Data, CIOs are turning to cognitive computing. Cognitive computing’s ability to securely extract insights, understand natural language, and get smarter each time it’s used is the next, logical step for Big Data.
The 4th International Internet of @ThingsExpo, co-located with the 17th International Cloud Expo - to be held November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA - announces that its Call for Papers is open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
There's no doubt that the Internet of Things is driving the next wave of innovation. Google has spent billions over the past few months vacuuming up companies that specialize in smart appliances and machine learning. Already, Philips light bulbs, Audi automobiles, and Samsung washers and dryers can communicate with and be controlled from mobile devices. To take advantage of the opportunities the Internet of Things brings to your business, you'll want to start preparing now.
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo in Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 17th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal an...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at @ThingsExpo, Robin Raymond, Chief Architect at Hookflash, will walk through the shifting landscape of traditional telephone and voice services ...
The 17th International Cloud Expo has announced that its Call for Papers is open. 17th International Cloud Expo, to be held November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, APM, APIs, Microservices, Security, Big Data, Internet of Things, DevOps and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportunity. Submit your speaking proposal today!
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo, June 9-11, 2015, at the Javits Center in New York City. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be
The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
SYS-CON Events announced today that DragonGlass, an enterprise search platform, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. After eleven years of designing and building custom applications, OpenCrowd has launched DragonGlass, a cloud-based platform that enables the development of search-based applications. These are a new breed of applications that utilize a search index as their backbone for data retrieval. They can easily adapt to new data sets and provide access to both structured and unstruc...
Container frameworks, such as Docker, provide a variety of benefits, including density of deployment across infrastructure, convenience for application developers to push updates with low operational hand-holding, and a fairly well-defined deployment workflow that can be orchestrated. Container frameworks also enable a DevOps approach to application development by cleanly separating concerns between operations and development teams. But running multi-container, multi-server apps with containers is very hard. You have to learn five new and different technologies and best practices (libswarm, sy...
Buzzword alert: Microservices and IoT at a DevOps conference? What could possibly go wrong? In this Power Panel at DevOps Summit, moderated by Jason Bloomberg, the leading expert on architecting agility for the enterprise and president of Intellyx, panelists will peel away the buzz and discuss the important architectural principles behind implementing IoT solutions for the enterprise. As remote IoT devices and sensors become increasingly intelligent, they become part of our distributed cloud environment, and we must architect and code accordingly. At the very least, you'll have no problem fil...
There's Big Data, then there's really Big Data from the Internet of Things. IoT is evolving to include many data possibilities like new types of event, log and network data. The volumes are enormous, generating tens of billions of logs per day, which raise data challenges. Early IoT deployments are relying heavily on both the cloud and managed service providers to navigate these challenges. In her session at Big Data Expo®, Hannah Smalltree, Director at Treasure Data, discussed how IoT, Big Data and deployments are processing massive data volumes from wearables, utilities and other machines...
SYS-CON Events announced today that MetraTech, now part of Ericsson, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Ericsson is the driving force behind the Networked Society- a world leader in communications infrastructure, software and services. Some 40% of the world’s mobile traffic runs through networks Ericsson has supplied, serving more than 2.5 billion subscribers.
The worldwide cellular network will be the backbone of the future IoT, and the telecom industry is clamoring to get on board as more than just a data pipe. In his session at @ThingsExpo, Evan McGee, CTO of Ring Plus, Inc., discussed what service operators can offer that would benefit IoT entrepreneurs, inventors, and consumers. Evan McGee is the CTO of RingPlus, a leading innovative U.S. MVNO and wireless enabler. His focus is on combining web technologies with traditional telecom to create a new breed of unified communication that is easily accessible to the general consumer. With over a de...
Disruptive macro trends in technology are impacting and dramatically changing the "art of the possible" relative to supply chain management practices through the innovative use of IoT, cloud, machine learning and Big Data to enable connected ecosystems of engagement. Enterprise informatics can now move beyond point solutions that merely monitor the past and implement integrated enterprise fabrics that enable end-to-end supply chain visibility to improve customer service delivery and optimize supplier management. Learn about enterprise architecture strategies for designing connected systems tha...
Cloud is not a commodity. And no matter what you call it, computing doesn’t come out of the sky. It comes from physical hardware inside brick and mortar facilities connected by hundreds of miles of networking cable. And no two clouds are built the same way. SoftLayer gives you the highest performing cloud infrastructure available. One platform that takes data centers around the world that are full of the widest range of cloud computing options, and then integrates and automates everything. Join SoftLayer on June 9 at 16th Cloud Expo to learn about IBM Cloud's SoftLayer platform, explore se...
SYS-CON Media announced today that 9 out of 10 " most read" DevOps articles are published by @DevOpsSummit Blog. Launched in October 2014, @DevOpsSummit Blog offers top articles, news stories, and blog posts from the world's well-known experts and guarantees better exposure for its authors than any other publication. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce softw...
15th Cloud Expo, which took place Nov. 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA, expanded the conference content of @ThingsExpo, Big Data Expo, and DevOps Summit to include two developer events. IBM held a Bluemix Developer Playground on November 5 and ElasticBox held a Hackathon on November 6. Both events took place on the expo floor. The Bluemix Developer Playground, for developers of all levels, highlighted the ease of use of Bluemix, its services and functionality and provide short-term introductory projects that developers can complete between sessions.