Click here to close now.

Welcome!

Java Authors: Pat Romanski, Sematext Blog, Liz McMillan, Elizabeth White, Plutora Blog

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
When it comes to the Internet of Things, hooking up will get you only so far. If you want customers to commit, you need to go beyond simply connecting products. You need to use the devices themselves to transform how you engage with every customer and how you manage the entire product lifecycle. In his session at @ThingsExpo, Sean Lorenz, Technical Product Manager for Xively at LogMeIn, will show how “product relationship management” can help you leverage your connected devices and the data they generate about customer usage and product performance to deliver extremely compelling and reliabl...
PubNub on Monday has announced that it is partnering with IBM to bring its sophisticated real-time data streaming and messaging capabilities to Bluemix, IBM’s cloud development platform. “Today’s app and connected devices require an always-on connection, but building a secure, scalable solution from the ground up is time consuming, resource intensive, and error-prone,” said Todd Greene, CEO of PubNub. “PubNub enables web, mobile and IoT developers building apps on IBM Bluemix to quickly add scalable realtime functionality with minimal effort and cost.”
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...
“In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Intelligent Systems Services 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. Established in 1994, Intelligent Systems Services Inc. is located near Washington, DC, with representatives and partners nationwide. ISS’s well-established track record is based on the continuous pursuit of excellence in designing, implementing and supporting nationwide clients’ mission-critical systems. ISS has completed many successful projects in Healthcare, Commercial, Manufacturing, ...
DevOps tends to focus on the relationship between Dev and Ops, putting an emphasis on the ops and application infrastructure. But that’s changing with microservices architectures. In her session at DevOps Summit, Lori MacVittie, Evangelist for F5 Networks, will focus on how microservices are changing the underlying architectures needed to scale, secure and deliver applications based on highly distributed (micro) services and why that means an expansion into “the network” for DevOps.
With several hundred implementations of IoT-enabled solutions in the past 12 months alone, this session will focus on experience over the art of the possible. Many can only imagine the most advanced telematics platform ever deployed, supporting millions of customers, producing tens of thousands events or GBs per trip, and hundreds of TBs per month. With the ability to support a billion sensor events per second, over 30PB of warm data for analytics, and hundreds of PBs for an data analytics archive, in his session at @ThingsExpo, Jim Kaskade, Vice President and General Manager, Big Data & Ana...
For years, we’ve relied too heavily on individual network functions or simplistic cloud controllers. However, they are no longer enough for today’s modern cloud data center. Businesses need a comprehensive platform architecture in order to deliver a complete networking suite for IoT environment based on OpenStack. In his session at @ThingsExpo, Dhiraj Sehgal from PLUMgrid will discuss what a holistic networking solution should really entail, and how to build a complete platform that is scalable, secure, agile and automated.
We’re no longer looking to the future for the IoT wave. It’s no longer a distant dream but a reality that has arrived. It’s now time to make sure the industry is in alignment to meet the IoT growing pains – cooperate and collaborate as well as innovate. In his session at @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, will examine the key ingredients to IoT success and identify solutions to challenges the industry is facing. The deep industry expertise behind this presentation will provide attendees with a leading edge view of rapidly emerging IoT oppor...
In the consumer IoT, everything is new, and the IT world of bits and bytes holds sway. But industrial and commercial realms encompass operational technology (OT) that has been around for 25 or 50 years. This grittier, pre-IP, more hands-on world has much to gain from Industrial IoT (IIoT) applications and principles. But adding sensors and wireless connectivity won’t work in environments that demand unwavering reliability and performance. In his session at @ThingsExpo, Ron Sege, CEO of Echelon, will discuss how as enterprise IT embraces other IoT-related technology trends, enterprises with i...
The Internet of Things (IoT) is causing data centers to become radically decentralized and atomized within a new paradigm known as “fog computing.” To support IoT applications, such as connected cars and smart grids, data centers' core functions will be decentralized out to the network's edges and endpoints (aka “fogs”). As this trend takes hold, Big Data analytics platforms will focus on high-volume log analysis (aka “logs”) and rely heavily on cognitive-computing algorithms (aka “cogs”) to make sense of it all.
The Internet of Everything (IoE) brings together people, process, data and things to make networked connections more relevant and valuable than ever before – transforming information into knowledge and knowledge into wisdom. IoE creates new capabilities, richer experiences, and unprecedented opportunities to improve business and government operations, decision making and mission support capabilities. In his session at @ThingsExpo, Gary Hall, Chief Technology Officer, Federal Defense at Cisco Systems, will break down the core capabilities of IoT in multiple settings and expand upon IoE for bo...
Sensor-enabled things are becoming more commonplace, precursors to a larger and more complex framework that most consider the ultimate promise of the IoT: things connecting, interacting, sharing, storing, and over time perhaps learning and predicting based on habits, behaviors, location, preferences, purchases and more. In his session at @ThingsExpo, Tom Wesselman, Director of Communications Ecosystem Architecture at Plantronics, will examine the still nascent IoT as it is coalescing, including what it is today, what it might ultimately be, the role of wearable tech, and technology gaps stil...
One of the biggest impacts of the Internet of Things is and will continue to be on data; specifically data volume, management and usage. Companies are scrambling to adapt to this new and unpredictable data reality with legacy infrastructure that cannot handle the speed and volume of data. In his session at @ThingsExpo, Don DeLoach, CEO and president of Infobright, will discuss how companies need to rethink their data infrastructure to participate in the IoT, including: Data storage: Understanding the kinds of data: structured, unstructured, big/small? Analytics: What kinds and how responsiv...
Cloudian, Inc., the leading provider of hybrid cloud storage solutions, today announced availability of Cloudian HyperStore 5.1 software. HyperStore 5.1 is an enhanced Amazon S3-compliant, plug-and-play hybrid cloud software solution that now features full Apache Hadoop integration. Enterprises can now transform big data into smart data by running Hadoop analytics on HyperStore software and appliances. This in-place analytics, with no need to offload data to other systems for Hadoop analyses, enables customers to derive meaningful business intelligence from their data quickly, efficiently and ...
Since 2008 and for the first time in history, more than half of humans live in urban areas, urging cities to become “smart.” Today, cities can leverage the wide availability of smartphones combined with new technologies such as Beacons or NFC to connect their urban furniture and environment to create citizen-first services that improve transportation, way-finding and information delivery. In her session at @ThingsExpo, Laetitia Gazel-Anthoine, CEO of Connecthings, will focus on successful use cases.
Sensor-enabled things are becoming more commonplace, precursors to a larger and more complex framework that most consider the ultimate promise of the IoT: things connecting, interacting, sharing, storing, and over time perhaps learning and predicting based on habits, behaviors, location, preferences, purchases and more. In his session at @ThingsExpo, Tom Wesselman, Director of Communications Ecosystem Architecture at Plantronics, will examine the still nascent IoT as it is coalescing, including what it is today, what it might ultimately be, the role of wearable tech, and technology gaps stil...
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.
Wearable devices have come of age. The primary applications of wearables so far have been "the Quantified Self" or the tracking of one's fitness and health status. We propose the evolution of wearables into social and emotional communication devices. Our BE(tm) sensor uses light to visualize the skin conductance response. Our sensors are very inexpensive and can be massively distributed to audiences or groups of any size, in order to gauge reactions to performances, video, or any kind of presentation. In her session at @ThingsExpo, Jocelyn Scheirer, CEO & Founder of Bionolux, will discuss ho...
The explosion of connected devices / sensors is creating an ever-expanding set of new and valuable data. In parallel the emerging capability of Big Data technologies to store, access, analyze, and react to this data is producing changes in business models under the umbrella of the Internet of Things (IoT). In particular within the Insurance industry, IoT appears positioned to enable deep changes by altering relationships between insurers, distributors, and the insured. In his session at @ThingsExpo, Michael Sick, a Senior Manager and Big Data Architect within Ernst and Young's Financial Servi...