I am a new contributor to the Stack Overflow community and I hope to receive your understanding.
I am creating a Java Swing application in which I am facing the following problem: I have a JMenuBar for my Java Swing application. This menu bar contains a so-called file JMenu and the file JMenu contains two more JMenus for creating and opening files. There is a screenshot of what I've described so far (in order if my explanation wasn't clear enough).
As you can see on the screenshot the "Create" and the "Open" menus aren't the same as the menus and menu items even though they have the same implementation. The background stays the same as the default one, but the foreground color changed.
This is the code:
private final ResourceBundle bundle;
private final Font font = new Font("K2D", Font.PLAIN, TextSizes.MENU_BAR_TEXT_SIZE.size);
private final Color foregroundColor = new Color(255, 255, 255);
private final Color backgroundColor = new Color(37, 37, 37);
public MenuBar(ResourceBundle bundle) {
this.bundle = bundle;
JMenu fileMenu = new JMenu(bundle.getString("menuBarFileMenu"));
setupMenu(fileMenu);
JMenu fileCreateMenu = new JMenu(bundle.getString("fileMenuCreate"));
setupMenu(fileCreateMenu);
fileCreateInvoice = new JMenuItem(bundle.getString("fileMenuInvoice"));
setupMenuItem(fileCreateInvoice);
fileCreateMenu.add(fileCreateInvoice);
JMenu fileOpenMenu = new JMenu(bundle.getString("fileMenuOpen"));
setupMenu(fileOpenMenu);
fileOpenInvoice = new JMenuItem(bundle.getString("fileMenuInvoice"));
setupMenuItem(fileOpenInvoice);
fileOpenMenu.add(fileOpenInvoice);
fileMenu.add(fileCreateMenu);
fileMenu.add(fileOpenMenu);
fileMenu.addSeparator();
}
private void setupMenu(@NotNull JMenu menu) {
menu.setFont(font);
menu.setBackground(backgroundColor);
menu.setForeground(foregroundColor);
menu.getPopupMenu().setBorder(null);
menu.setBorder(null);
}
private void setupMenuItem(@NotNull JMenuItem menuItem) {
menuItem.setFont(font);
menuItem.setBackground(backgroundColor);
menuItem.setForeground(foregroundColor);
menuItem.setBorderPainted(false);
menuItem.setBorder(null);
}
How could I fix this problem?
I've already tried to change properties with menu.getComponent().setBackground() and menu.getComponent().setForeground() method. I've done the same exact process that both methods implement in order to achieve the desired result. I've tried to mess up with UIManager settings which didn't give me any good results.
The problem is resolved. The fileCreateMenu
and the fileOpenMenu
must have opaque
property set to true with the method setOpaque()
.