How to add separator in a ToolBar with Java?


To add a separator, use the addSeparator() method. Let us first create a toolbar −

JToolBar toolbar = new JToolBar();

Now, we will create some components and set a separator to separate them as shown below −

toolbar.add(new JTextArea(" Add name here"));
toolbar.add(new JButton("Submit Name"));
toolbar.addSeparator();
toolbar.add(new JTextArea(" Add age here"));
toolbar.add(new JButton("Submit Age"));

The following is an example to add separator in a ToolBar with Java −

Example

package my;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
public class SwingDemo {
   public static void main(String[] args) {
      JPanel panel = new JPanel(new BorderLayout());
      JToolBar toolbar = new JToolBar();
      panel.add(toolbar, BorderLayout.PAGE_START);
      toolbar.add(new JTextArea(" Add name here"));
      toolbar.add(new JButton("Submit Name"));
      toolbar.addSeparator();
      toolbar.add(new JTextArea(" Add age here"));
      toolbar.add(new JButton("Submit Age"));
      toolbar.add(new JButton("Clear"));
      toolbar.add(new JButton("Refresh"));
      toolbar.addSeparator();
      JFrame frame = new JFrame(BorderLayout.PAGE_START);
      frame.setTitle("Separator");
      frame.setContentPane(panel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationByPlatform(true);
      frame.pack();
      frame.setSize(550, 200);
      frame.setVisible(true);
   }
}

Output

Updated on: 30-Jul-2019

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements