Swing ToolBar with Image button : JToolBar « Swing « Java Tutorial






import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JToolBar;

public class SwingBar extends JFrame {
  Container frameContainer;

  JToolBar toolBar = new JToolBar();

  String[] iconFiles = { "new.gif", "open.gif", "save.gif", "cut.gif", "copy.gif", "paste.gif" };

  String[] buttonLabels = { "New", "Open", "Save", "Cut", "Copy", "Paste" };

  ImageIcon[] icons = new ImageIcon[iconFiles.length];

  JButton[] buttons = new JButton[buttonLabels.length];

  JMenuBar menuBar = new JMenuBar();

  JMenu fileMenu = new JMenu("File");

  JMenuItem fileExit = new JMenuItem("Exit");

  public SwingBar() {
    fileMenu.add(fileExit);
    menuBar.add(fileMenu);
    setJMenuBar(menuBar);

    frameContainer = getContentPane();
    frameContainer.setLayout(new BorderLayout());
    for (int i = 0; i < buttonLabels.length; ++i) {
      icons[i] = new ImageIcon(iconFiles[i]);
      buttons[i] = new JButton(icons[i]);
      buttons[i].setToolTipText(buttonLabels[i]);
      if (i == 3)
        toolBar.addSeparator();
      toolBar.add(buttons[i]);
    }
    frameContainer.add("North", toolBar);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    fileExit.addActionListener(new MenuItemHandler());

    setSize(500, 500);
    setVisible(true);
  }

  public static void main(String[] args) {
    SwingBar app = new SwingBar();
  }

  public class MenuItemHandler implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      String cmd = e.getActionCommand();
      if (cmd.equals("Exit"))
        System.exit(0);
    }
  }
}








14.57.JToolBar
14.57.1.JToolbar: Toolbars provide a quick access to the most frequently used commands.
14.57.2.A Complete JToolBar Usage ExampleA Complete JToolBar Usage Example
14.57.3.Create a vertical toolbar
14.57.4.Adding separator for JToolBarAdding separator for JToolBar
14.57.5.Add various buttons to the toolbar
14.57.6.Customizing Tool BarsCustomizing Tool Bars
14.57.7.Toolbar with CheckBoxToolbar with CheckBox
14.57.8.Swing ToolBar with Image button
14.57.9.Preventing a JToolbar Container from Floating
14.57.10.Highlighting Buttons in a JToolbar Container While Under the Cursor
14.57.11.Determining When a Floatable JToolBar Container Changes Orientation
14.57.12.Customizing JToolBar Look and Feel
14.57.13.This class represents a separator for the toolbar buttons.
14.57.14.ToolBar button