Issue with JMenuBar Shifting on Mac OS X
When attempting to move a JMenuBar to the screen menu bar in a Mac OS X environment, a blank space is often left behind where the menu would reside within the window. This issue can be resolved by establishing the property "apple.laf.useScreenMenuBar" at the appropriate time.
Solution
To address this problem, set the property "apple.laf.useScreenMenuBar" at program launch using one of the following methods:
java -Dapple.laf.useScreenMenuBar=true -jar MyApplication.jar
<key>Properties</key> <dict> <key>apple.laf.useScreenMenuBar</key> <string>true</string> ... </dict>
Additional Considerations
It's important to note that setting the property after the application has launched may not be effective. The following code demonstrates a correct implementation where no blank space is present:
import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; /** @see http://stackoverflow.com/questions/8955638 */ public class NewMain { public static void main(String[] args) { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty( "com.apple.mrj.application.apple.menu.about.name", "Name"); EventQueue.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame("Gabby"); final JPanel dm = new JPanel() { @Override public Dimension getPreferredSize() { return new Dimension(320, 240); } }; dm.setBorder(BorderFactory.createLineBorder(Color.blue, 10)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(dm); frame.pack(); frame.setLocationByPlatform(true); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); frame.setJMenuBar(menuBar); frame.setVisible(true); } }); } }
The above is the detailed content of Why does my JMenuBar leave a blank space on the Mac OS X screen menu bar?. For more information, please follow other related articles on the PHP Chinese website!