Java Swing GUI

JToolBar – Java Swing – Example

In this tutorial, we are going to see an example of JToolBar in Java Swing. JToolBar is part of the Java Swing package. JToolBar is an implementation of a toolbar. The JToolBar is a group of commonly used components such as buttons or a drop-down menu. JToolBar can be dragged to different locations by the user.


 
 

JToolBar constructors class:
JToolBar constructors
Description
JToolBar() Creates a new toolbar with a horizontal orientation
JToolBar(int o) Creates a new toolbar with a specified orientation
JToolBar(String n) Creates a new toolbar with the specified name
JToolBar(String n, int o) Creates a new toolbar with the specified name and orientation.

 

Example of JToolBar in Java Swing:
import java.awt.*;
import javax.swing.*;

public class Main 
{
  public static void main(final String args[]) 
  {
    JFrame f = new JFrame("JToolBar Example");
    
    JToolBar tb = new JToolBar();
    tb.setRollover(true);
    
    tb.add(new JButton("Button 1"));
    tb.addSeparator();
    tb.add(new JButton("Button 2"));
    tb.add(
      new JComboBox(
        new String[] { "item1", "item2", "item3", "item4" }
      )
    );
    Container c = f.getContentPane();
    // add the toolbar to the container
    c.add(tb, BorderLayout.NORTH);
    JTextArea text = new JTextArea();
    JScrollPane p = new JScrollPane(text);
    c.add(p, BorderLayout.EAST);
    
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(400, 200);
    f.setVisible(true);
  }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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