Creating an offscreen frame in Java (or: how to avoid a blank menu on a Mac, when all application windows are closed)?

后端 未结 6 1850
囚心锁ツ
囚心锁ツ 2020-12-19 08:55

I am making a Mac application, and I want my menu bar to look right.

Any Mac user knows the menu bar should be in the top screen menu. Setting apple.laf.useSc

6条回答
  •  春和景丽
    2020-12-19 09:15

    This code works in Java 7:

    if( isMac ) {
        //This creates an invisible frame so that we always have a menu bar visible
        JFrame menuFrame = new JFrame();
        menuFrame.setUndecorated( true );
        menuFrame.setJMenuBar( defaultMenuBar );
        AWTUtilities.setWindowOpaque( menuFrame, false );
        menuFrame.setBounds( 0,0,1,1 );
        menuFrame.setVisible( true );
    }
    

    Just call this before you open any other windows, and it will stay in the background and automatically become the focused window when others are closed. You can still use the com.apple.eawt.Application.getApplication().setDefaultMenuBar(menuBar) method in your application so that you don't need to call setJMenuBar() on each JFrame.

提交回复
热议问题