Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change background and text color of JMenuBar and JMenu objects inside it

How can I set custom background color for JMenuBar and JMenu objects inside it? I tried .setBackgroundColor and it does not work!

like image 525
KernelPanic Avatar asked Nov 27 '22 05:11

KernelPanic


2 Answers

Create a new class that extends JMenuBar:

public class BackgroundMenuBar extends JMenuBar {
    Color bgColor=Color.WHITE;

    public void setColor(Color color) {
        bgColor=color;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(bgColor);
        g2d.fillRect(0, 0, getWidth() - 1, getHeight() - 1);

    }
}

Now you use this class instead of JMenuBar and set the background color with setColor().

like image 60
D180 Avatar answered Dec 05 '22 18:12

D180


You would probably need to change opacity of menu items, ie:

JMenuItem item= new JMenuItem("Test");
item.setOpaque(true);
item.setBackground(Color.CYAN);

You can also achieve that globally using UIManager, for example:

UIManager.put("MenuItem.background", Color.CYAN);
UIManager.put("MenuItem.opaque", true);
like image 33
tenorsax Avatar answered Dec 05 '22 16:12

tenorsax