JMenuBar Background Image Example

Several example about JMenuBar background image I have found so far have one limitation that when you maximize or re-size JFrame, the background image does not fit the width of JFrame. Here I have used Dimension class to overcome the limitation. Hope you will enjoy.

JMenuBarBackgroundDemo.java

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

public class JMenuBarBackgroundDemo extends JFrame {

    private JMenu mnFile;
    private JMenuItem mntmNew;
    private JMenuItem mntmSave;
    private JMenuBar menuBar;

    /**
     * Create the frame.
     */
    public JMenuBarBackgroundDemo() {
        super("Background Image JMenuBar");
        setResizable(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 482, 361);

        menuBar = new JMenuBar() {

            @Override
            public void paintComponent(Graphics g) {
                Dimension size = this.getSize();
                g.drawImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/menubg.png")), 0, 0, size.width, size.height, this);
            }
        };

        mnFile = new JMenu("File");
        mntmNew = new JMenuItem("New");
        mntmSave = new JMenuItem("Save");
        
        menuBar.add(mnFile);        
        mnFile.add(mntmNew);        
        mnFile.add(mntmSave);
        
        setJMenuBar(menuBar);
        setLocationRelativeTo(null);
    }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    JMenuBarBackgroundDemo frame = new JMenuBarBackgroundDemo();
                    frame.setVisible(true);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Screenshot:
jmenubar_background_image

 

admin

Hello! I am Md. Abdul Bari; founder and admin of javaknowledge; currently providing training as a J2EE faculty in The Computers Ltd. Dhaka, Bangladesh under an IT Scholarship project provided by IDB-BISEW. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

More Posts - Website

Follow Me:
TwitterFacebookGoogle Plus

8,952` Total Views

2 comments

Leave a Reply

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


6 × five =