Tuesday , November 21 2017
Home / java / Java Swing JToolBar Example

Java Swing JToolBar Example

In this tutorial I am going to show you how to create Toolbar using Java. Toolbars are used to display commonly used actions or controls.

Swing JToolBar provides component that allows to maintain commonly used actions like aliment, save, changing fonts and etc..

Swing JToolBar Example :


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

class MyFrameToolBarDemo extends JFrame {
    JToolBar toolbar;
    JButton New, Open, Save;
    JToggleButton Left, Center, Right;
    JComboBox fonts;
    ButtonGroup group;

    MyFrameToolBarDemo() {
        super("JToolbar Demo");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        toolbar = new JToolBar();

        New = new JButton(new ImageIcon(
                "D:\\images\\NEW.GIF"));
        Open = new JButton(new ImageIcon(
                "D:\\images\\OPEN.gif"));
        Save = new JButton(new ImageIcon(
                "D:\\images\\SAVE.gif"));

        Left = new JToggleButton(new ImageIcon(
                "D:\\images\\LEFT.gif"));
        Center = new JToggleButton(
                new ImageIcon(
                        "D:\\images\\CENTER.gif"));
        Right = new JToggleButton(new ImageIcon(
                "D:\\images\\RIGHT.gif"));

        group = new ButtonGroup();

        group.add(Left);
        group.add(Center);
        group.add(Right);

        fonts = new JComboBox();
        fonts.addItem("Arial");
        fonts.addItem("Times New Roman");
        fonts.addItem("Comic Sans Ms");

        toolbar.add(New);
        toolbar.add(Open);

        toolbar.addSeparator();

        toolbar.add(Save);

        toolbar.addSeparator();

        toolbar.add(Left);
        toolbar.add(Center);
        toolbar.add(Right);

        toolbar.addSeparator();

        toolbar.add(fonts);

        getContentPane().add(toolbar, BorderLayout.NORTH);
        pack();
        setVisible(true);
    }
}

public class ToolBarDemo {
    public static void main(String args[]) throws Exception {
        new MyFrameToolBarDemo();
    }
}

Output :

JToolBar Example

Font :

JToolBar Example 2

Happy Learning 🙂

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Recommended

How to add dynamic files to JTree

In the previous tutorial, we learn about a simple JTree. This tutorial is for adding …

Leave a Reply

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