Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Java: How to check whether a JFrame's menu bar is displayed in the systems menubar or in the frame itself?

A JFrame in (From Swing) allows you to set a menu bar (Instance of MenuBar using JFrame.setMenuBar(mb);). This menu bar can appear in different locations depending on the system it's running on. If the operating system the appliation is running on has a menu bar on top of the screen, this menu bar set in the JFrame usually appears in this menu bar. If this is not supported, the menu bar will be shown in the top of the frame itself.

You can see the different behaviours on different systems in the example bellow:

MenuBar on WindowsMenuBar on Mac OS X

This is an example of the code I use to set up the menu bar:

// Initialize a menu bar
MenuBar mb = new MenuBar();

// Initialize the menu and some menu items, add these to the menu bar
Menu m = new Menu("Menu 1");
MenuItem mi1 = new MenuItem("Menu Item 1");
MenuItem mi2 = new MenuItem("Menu Item 2");
MenuItem mi3 = new MenuItem("Menu Item 3");

// Set the menu bar

My question is: How do I check whether the menu bar will be shown in the frame itself or in the system's menu bar (if supported)? It would be great if there's any possible way to check this without initializing and defining a menu bar. Maybe this is impossible, if that is the case, is it possible to check for this same problem after a menu bar has been defined?

like image 208
Tim Visée Avatar asked Mar 22 '23 13:03

Tim Visée

1 Answers

As shown here, apple.laf.useScreenMenuBar specifies a Mac OS feature that displays an existing JMenuBar atop the screen, where a Mac user expects to see it. Although it should be irrelevant to your application, the only time the menu bar is displayed there is when you put it there. A suitable cross-platform predicate might look like this:

if (System.getProperty("os.name").startsWith("Mac OS X")) {
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("apple.awt.graphics.UseQuartz", "true");
    // etc.
like image 193
trashgod Avatar answered Apr 06 '23 14:04