I have a Java program in which I enable and disable menus. It works nicely under Windows, but I have some problems when running it on a Mac.
Here’s a piece of code that demonstrates the problem:
import javax.swing.*;
import java.awt.event.*;
public class PopTest extends JFrame {
JMenu menu1;
JMenu menu2;
public PopTest() {
menu1 = new JMenu("Menu 1");
menu2 = new JMenu("Menu 2");
menu2.setEnabled(false);
menu1.add(new JMenuItem(new AbstractAction("With popup") {
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(PopTest.this,"Popup","Popup",JOptionPane.ERROR_MESSAGE);
menu2.setEnabled(true);
menu2.add(new JMenuItem("New item"));
}
}));
menu1.add(new JMenuItem(new AbstractAction("Without popup") {
public void actionPerformed(ActionEvent event) {
menu2.setEnabled(true);
menu2.add(new JMenuItem("New item"));
}
}));
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu1);
menuBar.add(menu2);
setJMenuBar(menuBar);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args) {
try {
System.setProperty("apple.laf.useScreenMenuBar", "true");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e) {
System.out.println("Exception: " + e.getMessage());
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new PopTest();
}
});
}
}
This is what the program does:
The program has two menus, “Menu 1” and “Menu 2”. From the outset, Menu 1 is enabled and Menu 2 is disabled.
Menu 1 has two items that do almost the same thing: They enable Menu 2 and add a menu item to it. The difference is that one of the items display a message dialog before enabling Menu 2, whereas the other item does not.
Now, compile the program and try this:
Experiment 1: Select Menu 1 > Without popup. Now click on Menu 2 and you will see that the menu has an enabled menu item called “New item”.
Expermiment 2: Close the program! Start the program again. Select Menu 1 > With popup. Click OK in the message dialog. Now click on Menu 2 and you will see that the menu has a disabled menu item called “New item”. Click elsewhere on your desktop so that the application looses focus. Click in the application. Click on Menu 2 and you will see that the menu item is now enabled.
In experiment 2 it is very important that the application does not loose focus before you are instructed to click elsewhere on your desktop. Otherwise you will not see the problem.
Why is the menu item in Menu 2 disabled in the second experiment? Is this a bug? I’m using OS X 10.8.2 (Mountain Lion) and Java 1.7.0_09.
I can replicate the issue in Java 7, but not Java 6. I don’t understand why it’s doing this, but one thing that fixed it for me was to move setEnabled() above JOptionPane.showMessageDialog():