JToolBar in Java Swing

A JToolBar in Java Swing is a graphical component used to create toolbars in GUI applications. Toolbars typically contain buttons and other controls for quick access to frequently used actions. Following is a basic example demonstrating the usage of JToolBar:

import java.awt.BorderLayout;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;

public class JToolBarDemo extends JFrame {
	public JToolBarDemo() {
		setTitle("JToolBar Demo");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Create a toolbar
		JToolBar toolBar = new JToolBar();

		final int toolBarIconWidth = 20;
		final int toolBarIconHeight = toolBarIconWidth;

		// Create buttons for the toolbar
		ImageIcon openIcon = new ImageIcon("open.png");
		openIcon = new ImageIcon(
				openIcon.getImage().getScaledInstance(toolBarIconWidth, toolBarIconHeight, Image.SCALE_SMOOTH));
		JButton openButton = new JButton(openIcon);

		ImageIcon saveIcon = new ImageIcon("save.png");
		saveIcon = new ImageIcon(
				saveIcon.getImage().getScaledInstance(toolBarIconWidth, toolBarIconHeight, Image.SCALE_SMOOTH));
		JButton saveButton = new JButton(saveIcon);

		ImageIcon printIcon = new ImageIcon("print.png");
		printIcon = new ImageIcon(
				printIcon.getImage().getScaledInstance(toolBarIconWidth, toolBarIconHeight, Image.SCALE_SMOOTH));
		JButton printButton = new JButton(printIcon);

		// Add buttons to the toolbar
		toolBar.add(openButton);
		toolBar.add(saveButton);
		toolBar.add(printButton);

		// Add the toolbar to the frame
		add(toolBar, BorderLayout.NORTH);

		setSize(300, 200);
		setLocationRelativeTo(null); // Center the window
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(() -> {
			new JToolBarDemo().setVisible(true);
		});
	}

}

Output:

JToolBar in java swing

Note: To make it work with the icon, save your icon images in the same directory where JToolBarDemo.java file is there and it should work.

If it does not work, feel free to write a comment. I will try to response as earlier as I can.

Thank you.


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments