Adding a background image to a JToolBar

Override the JToolBar’s method paintComponent, draw the image using g.drawImage and call the superclass’ paintComponent. This is similar to the JPanel implementation.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
 
   public static void main(String []args) {
      Main main = new Main();
      main.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent ev) {
            System.exit(0);
         }
      });
 
      main.pack();
      main.show(); 
   }
 
   private ImageIcon ii = new ImageIcon("mong.jpg");
 
   public Main() {
      super("ToolBar Background Image");
 
      getContentPane().setLayout(new BorderLayout());
 
      //
      // could also use an anonymous class...e.g.,
      // JToolBar toolbar = new JToolBar() {
      //     public void paintComponent(Graphics g) {
      //         ... see Class below...
      //     }
      // };
      //
      JToolBar toolbar = new ToolBarWithBgImage("My Toolbar", JToolBar.HORIZONTAL, ii);
      getContentPane().add(toolbar, BorderLayout.NORTH);
 
      toolbar.add(new JButton("Item 1"));
      toolbar.add(new JButton("Item 2"));
      toolbar.addSeparator();
      toolbar.add(new JButton("Item 3"));  
   }
 
   /**
    * This implementation stretches the image to fit the panel.
    * Could modify this to "tile" the image, center the image, etc.
    */
   class ToolBarWithBgImage extends JToolBar {
 
      private ImageIcon bgImage;
 
      ToolBarWithBgImage(String name, int orientation, ImageIcon ii) {
         super(name, orientation);
         this.bgImage = ii;
         setOpaque(true);
      }
 
      public void paintComponent(Graphics g) {
         super.paintComponent(g);
         if (bgImage != null) {
            Dimension size = this.getSize();
            g.drawImage(bgImage.getImage(), 0,0, size.width, size.height, this);
         }
      }
   }
}