JToolBar in Java with Example using NetBeans

JToolBar in Java:

With the javax.swing.JToolBar class, Java provides a so-called toolbar. This component is used to make frequently used functions directly available in a bar.

You can find an example of the use of a toolbar in programs for editing graphics (e.g Paint). There you will find various tools for editing graphics (e.g eraser). Toolbars are also usually available in text editing programs, via which the user can change the font, color, or size, for example. The individual tools are usually represented by appropriate icons.

If you are developing an application, you should consider whether there are also functionalities that are frequently used when using the program. If you integrate this in a toolbar, you increase the ease of use because the user does not have to look for the function in the menu bar first.

JToolBar Constructors:

constructor description
JToolBar(int orientation) Here the constructor is passed a class constant (HORIZONTAL or VERTICAL) that specifies the orientation of the toolbar. By default, the alignment is set to horizontal.
JToolBar(String name) A character string is passed to the constructor, which is displayed as the title if the JToolBar is no longer coupled to the parent window and is displayed in its own window.
JToolBar(String name, int orientation) This constructor combines the two constructors above.

Example: how to use JToolBar in java using NetBeans:

As you may have noticed, our import statements have shrunk a lot. This is because we save ourselves from a lot of import statements by instead importing the entire swing package using the import javax.swing.* command. The asterisk serves as a placeholder for all classes in the respective package. The short variant with placeholders is recommended if you use many classes from a package to keep the source code clear. 

In our example, we created a toolbar with 5 items and added it to our dialog. We used buttons ( JButton ) for this. We will go into more detail about buttons in the JButton article.

If you run the sample program, you should see the following picture:


The JToolBar is moveable you can place the toolbar anywhere in the window as you can see in the below images



The JToolBar class has two special methods: The setFloatable method expects a parameter of the data type boolean. If true is passed, which is the default, the user can move the toolbar. If false is passed, the toolbar is fixed at the default position.

The setRollover method also expects a parameter of data type boolean. If a true is passed here, the border of buttons is only drawn when the mouse pointer is moved over the corresponding button. By default, the value is set to false, so each button border is drawn.

The currently set status can be queried using the corresponding get methods.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button