How to Create ToolBar by Using JToolBar

Introduction to Toolbar

A toolbar provides users with common used features of application. We usually place a toolbar directly below the menu bars at the top of a frame. A toolbar acts as a container for other components including button, combobox and menu.

We often use toolbar as a selection tool e.g., text alignment in office suites application. In addition, we use toolbar to replace common used functions of menu to allow users to access features of application more quickly. In some applications, you will find that we use toolbar for navigation e.g., web browsers.

JToolBar class

In order to create a toolbar in Java Swing, you use JToolBar class. The JToolbar class supports two orientations: vertical and horizontal. You use the orientation attribute to maintain the current orientation of the toolbar.

You can add any component to the toolbar including button, combobox and menu. The order of component in the toolbar is determined by an integer index.

If you want to separate a group of related components in the toolbar, you can use JToolBar’s own separator by calling method addSeperator().

JToolBar also supports floatable toolbar. If you don’t want the toolbar floatable, you can use method setFloatable(false). 

It is highly recommended to place a toolbar in a container that supports BorderLayout. Because when you drag a toolbar, Swing will place the toolbar at either north, south, east or west side of the container.

Here are constructors of JToolBar class:

JToolBar()Creates a new toolbar with default horizontal orientation.
JToolBar(int orientation)Creates a new toolbar with a given orientation.
JToolBar(String name)Creates a new toolbar with a given name.
JToolBar(String name, int orientation)Creates a new toolbar with a given name and orientation

JToolBar Demo Application

Here is the screenshot of the JToolBar demo application:

JToolBar Demo

In this tutorial, we have shown you how to use JToolBar class to create toolbars for Java swing application.