I'm trying to populate a sub-menu dynamically, and in case there are no elements in it, I want to add a disabled JMenuItem in it with the text "(empty)". However, since the L&F is set to the System L&F (Windows, in my case), the JMenuItem highlights on mouseover. How do I avoid this? It works exactly as desired without setting L&F, but the fact that the L&F is set to that of the system is not something that I can change (since this is part of something larger).
Here's an SSCCE:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class HelpMenuItem {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
protected static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JFrame frame = new JFrame();
JMenuBar menuBar = new JMenuBar();
menuBar.setVisible(true);
JMenu menu = new JMenu("Test");
JMenu sub = new JMenu("SubMenu");
JMenuItem empty = new JMenuItem("(empty)");
empty.setEnabled(false);
menuBar.add(menu);
menu.add(sub);
sub.add(empty);
frame.setJMenuBar(menuBar);
JPanel panel = new JPanel();
panel.add(new JLabel("Test"));
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
}
You must set the LAF before
you create a component. Your SSCCE incorrectly illustrates your problem.
If you do set the LAF first then you will notice a different behaviour on Windows. All you will see is the "focus border" of the menu item being painted.
To disable the painting of the "focus border" you can use the UIManager. You can use:
UIManager.put("MenuItem.disabledAreNavigable", Boolean.FALSE);
For more information about the UIManager
, check out UIManager Defaults.