ADS

Set Background Image To Jmenubar

This illustrates setting background image to JMenuBar. For this we need to paint an background image on JMenuBar. 1 main step is far from background image.





 import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MenuBarBackground extends JFrame
{
JMenuBar mbar;
JMenu menu;
public MenuBarBackground()
{
setTitle("MenuBar Background");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);

mbar=new JMenuBar(){
public void paintComponent(Graphics g)
{
g.drawImage(Toolkit.getDefaultToolkit().getImage("F:/Wallpapers/violetpink.png"),0,0,this);
}
};

menu=new JMenu("Menu");
menu.setForeground(Color.white);
for(int i=1;i<=5;i++)
menu.add(new JMenuItem("MenuItem "+i));

mbar.add(menu);
setJMenuBar(mbar);
setSize(400,400);
}
public static void main(String args[])
{
new MenuBarBackground();
}
}

Output

 For this we need to paint an background image on JMenuBar Set Background Image to JMenuBar
Look at menubar background image

paintComponent(Graphics g): Takes java.awt.Graphics as parameter. This contains drawImage() method which takes java.awt.Image object, x,y axes and ImageObserver object. paint() is not used here because, if we use this, i could not see the Menu.

g.drawImage(Toolkit.getDefaultToolkit().getImage("F:/Wallpapers/violetpink.png"),0,0,this): Method of java.awt.Graphics class. java.awt.Toolkit is a class containing a static method getDefaultToolkit() which returns the object of that class only (java.awt.Toolkit). This class contains getImage() method which takes the path of the image file and returns the java.awt.Image object. My background image is located in F:\Wallpapers. You can notice / instead of \ this is because / is equal to \\ in Windows and similar operating systems. Next, 0,0 are the x,y co ordinates respectively. Try changing them, you'll notice the change. this represents current object which acts as ImageObserver.

In this way, we can set background image to JMenuBar easily in single step.

Subscribe to receive free email updates:

ADS