Skip to content

Instantly share code, notes, and snippets.

@ctrueden
Last active December 16, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctrueden/5445680 to your computer and use it in GitHub Desktop.
Save ctrueden/5445680 to your computer and use it in GitHub Desktop.
Here is a working solution for reusing the same JMenuBar across multiple windows: swap it upon window activation!
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.WindowConstants;
/**
* On OS X, with a screen menu bar, you can "hot-swap" a JMenuBar between
* multiple JFrames when each is activated. However, there is a brief flash each
* time the active window changes, where the menu bar disappears momentarily.
* But it is a small price to pay to be able to reuse the same menu bar!
*/
public class HotSwapJMenuBarOSX {
public static void main(final String[] args) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
final JMenuBar menuBar = new JMenuBar();
final JMenu file = new JMenu("File");
menuBar.add(file);
final JMenuItem fileNew = new JMenuItem("New");
file.add(fileNew);
final JFrame frame1 = new JFrame("First");
frame1.getContentPane().add(new JButton("First"));
frame1.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
final JFrame frame2 = new JFrame("Second");
frame2.getContentPane().add(new JButton("Second"));
frame2.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// hot-swap the menu bar to newly activated windows
final WindowListener listener = new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
((JFrame) e.getWindow()).setJMenuBar(menuBar);
}
};
frame1.addWindowListener(listener);
frame2.addWindowListener(listener);
final int offsetX = 200, offsetY = 50;
frame1.pack();
frame1.setLocation(offsetX, offsetY);
frame1.setVisible(true);
frame2.pack();
frame2.setLocation(frame1.getWidth() + offsetX + 10, offsetY);
frame2.setVisible(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment