Reputation: 23
I'm having some trouble with JMenuBar
and JMenu
in Ntebeans. I Just want to know can I set a custom background color for the JMenuBar
and the JMenu
objects inside it? I tried setBackgroundColor()
method and it does not work! I want set white color or transparent and I tried this too :
menubar.setBackground(Color.RED);
menu.setBackground(Color.yellow);
menubar.setOpaque(true);
menu.setOpaque(true);
and still like this
and i want some like this
I'm using Netbeans and when i set the preview, the JMenuBar set the background white JMenu Background White
But when i run the programm, still the same same color
Upvotes: 0
Views: 1398
Reputation: 309
You don't need to set opaque as true for JMenuBar and JMenuItem because they have true as opaque value by default. However, you have set explicitly opaque as true for JMenu because its default value is false. Thi simple code show you the default values of JMenuBar and JMenu and JMenuItem:
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("My menu");
menuBar.add(menu);
JMenuItem item1 = new JMenuItem("My item");
menu.add(item1);
System.out.println(" " + menuBar.isOpaque() + ", " + menu.isOpaque() + ", " + item1.isOpaque());
and you will see in the console: true, false, true. So to change the background of JMenu you have set its opaque value as true.
For your desired gui here a simple code:
public class TutoMenuBar extends JFrame {
public TutoMenuBar(String nameWindow) {
super(nameWindow);
initUI();
}
private void initUI() {
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu testingJMenu = new JMenu("Testing");
testingJMenu.setOpaque(true);
testingJMenu.setBackground(Color.BLUE);
menuBar.add(testingJMenu);
JMenu otherJMenu = new JMenu("Other");
otherJMenu.setOpaque(true);
otherJMenu.setBackground(Color.GREEN);
menuBar.add(otherJMenu);
JMenuItem menu_item_1JMenuItem = new JMenuItem("Menu Item 1");
menu_item_1JMenuItem.setBackground(new Color(251, 41, 255));
testingJMenu.add(menu_item_1JMenuItem);
JMenuItem menu_item_2JMenuItem = new JMenuItem("Menu Item 2");
menu_item_2JMenuItem.setBackground(new Color(251, 41, 255));
testingJMenu.add(menu_item_2JMenuItem);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
TutoMenuBar test = new TutoMenuBar("Test");
test.setVisible(true);
});
}
}
Upvotes: 0
Reputation: 1
It works for me using :
.setBackground(Color.RED)
and setOpaque(true)
Upvotes: 0