Using a JToolBar in a JFrame - Java Swing

Java examples for Swing:JToolBar

Description

Using a JToolBar in a JFrame

Demo Code

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;

public class Main extends JFrame {
  JToolBar toolBar = new JToolBar("My JToolBar");
  JTextArea msgText = new JTextArea(3, 45);

  public Main(String title) {
    super(title);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = this.getContentPane();
    prepareToolBar();//  w w  w  . j a v a2  s  .  c  o m

    contentPane.add(toolBar, BorderLayout.NORTH);
    contentPane.add(new JScrollPane(msgText), BorderLayout.CENTER);
    msgText.append("Move the toolbar around using its handle at the left end");
  }

  private void prepareToolBar() {
    Insets zeroInset = new Insets(0, 0, 0, 0);

    JButton newButton = new JButton("New");
    newButton.setMargin(zeroInset);
    newButton.setToolTipText("Add a new policy");

    JButton openButton = new JButton("Open");
    openButton.setMargin(zeroInset);
    openButton.setToolTipText("Open a policy");

    JButton exitButton = new JButton("Exit");
    exitButton.setMargin(zeroInset);
    exitButton.setToolTipText("Exit the application");

    exitButton.addActionListener(e -> System.exit(0));

    toolBar.add(newButton);
    toolBar.add(openButton);
    toolBar.addSeparator();
    toolBar.add(exitButton);

    toolBar.setRollover(true);
  }

  public static void main(String[] args) {
    Main frame = new Main("JToolBar Test");
    frame.pack();
    frame.setVisible(true);
  }
}

Related Tutorials