Academic Java    Java Tutorial  >  Swing  >  JToolBar

JToolBar Example

Java JToolBar EXAMPLE output The program shows a toolbar above a text area that we might imagine is used for text editing.

Each tool is a button containing an ImageIcon. The buttons would normally have listeners added to them.

Tool tip text has been added to the buttons. Tool tip text shows when the user hovers over any component to which it has been added.
// JToolbar Example
import java.awt.event.*; import javax.swing.*;
import java.awt.*; import java.io.*;

class JToolbarExample extends JFrame {

   JButton getButton(String fn) {
      ImageIcon ic=null;
      try {ic = new ImageIcon("images"+File.separator+fn);} 
      catch(Exception e) {ic=null;}
      return new JButton(ic);
   }

   public JToolbarExample() {
      super("Filer");
      setSize(400, 200);
      // setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JButton b0 = getButton("newfile.gif");
      JButton b1 = getButton("openfile.gif");
      JButton b2 = getButton("savefile.gif");

      b0.setToolTipText("New");
      b1.setToolTipText("Open file");
      b2.setToolTipText("Save file");

      JToolBar jtb = new JToolBar();
      jtb.add(b0);
      jtb.add(b1);
      jtb.add(b2);

      JTextArea ta = new JTextArea(10, 35);
      JScrollPane jsp = new JScrollPane(ta);

      setLayout(new BorderLayout());
      add(jtb,BorderLayout.NORTH);
      add(jsp,BorderLayout.CENTER);
      setVisible(true);
   }

   public static void main(String[] arguments) {
      JToolbarExample frame = new JToolbarExample();
   }
}