ADS

4 Ways To Create A Jtoolbar - Swing

How can we create a JToolBar? By using the JToolBar class!! Great, everyone knows it. But what else should we know? There are 5 methods that you should know and that do you know, that there are 4 ways of creating it? Yes, let us see how. But before, let us see those constructors and methods that you should know.

Constructors

 
JToolBar() // Simple toolbar
JToolBar(int orientation) // Horizontal or Vertical
JToolBar(String name) // Appears as title when undocked
JToolBar(String name,int orientation) // Title with orienation

Methods

 
public void addSeparator() // Adds a separator
public void setRollover(boolean rollover) // If false content area is not filled on hover, filled otherwise
public void setOrientation(int orientation) // Set horizontal/vertical 
public void setFloatable(boolean float) // Set whether the toolbar can be undocked to window or not
public void setMargin(Insets i) // Sets the space between toolbar's inner components and its border

 
import javax.swing.*;
import java.awt.*;
class JToolBarExample extends JFrame
{
JToolBar t1,t2,t3,t4;

    public JToolBarExample()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JToolBar Example");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
       
        t1=new JToolBar();
        t2=new JToolBar(JToolBar.VERTICAL);
        t3=new JToolBar("Toolbar 3");
        t4=new JToolBar("Toolbar 4",JToolBar.VERTICAL);
       
        for(int i=1;i<5;i++)
        {
            t1.add(new JButton("Button "+i));
            t1.addSeparator();
            t2.add(new JButton("Button "+i));
            t3.add(new JButton("Button "+i));
            t4.add(new JButton("Button "+i));
        }
       
        t1.setMargin(new Insets(10,10,10,10));
       
        t1.setRollover(false);
       
        t1.setFloatable(false);
       
        add(t1);
        add(t2);
        add(t3);
        add(t4);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new JToolBarExample();
    }
}

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)

Subscribe to receive free email updates:

ADS