Link to Wolfram Community version
getDefaultToolkit() through J/Link causes the Front End to lose focus. This is specific to OS X. Here is a minimal example (it needs to be run in a fresh kernel):
Needs["JLink`"] InstallJava; JLink`LoadJavaClass["java.awt.Toolkit", AllowShortContext -> False]; CreatePalette@Button["Press", java`awt`Toolkit`getDefaultToolkit]
This opens a palette with one button. Pressing this button for the first time causes all Front End windows to lose focus. As a side effect, the palette itself disappears. Note that palettes are only shown when the Front End is the foreground application.
The Mathematica application itself does not lose focus. It is still the active application, as evidenced by the text "Mathematica" in the OS X menu bar. However, the Front End behaves as if I had switched to a different application.
Since effectively it is the entire Front End that loses focus, and not just one notebook,
SetSelectedNotebook is of no help here.
Pressing the button (or calling
getDefaultToolkit()) a second time does not cause this behaviour.
The problem also occurs when evaluating
java`awt`Toolkit`getDefaultToolkit in a normal notebook. I showed it with a palette, because the fact the the palette disappears is very striking (and it is really this behaviour that I consider to be a problem for my application).
Is there a workaround for this problem?
I need to fix this for a palette I am working on. Due to this problem, the palette effectively disappears either immediately when it is opened from the Palettes menu or as soon as a button is used (depending on where this code is called). This is not harmful, but it would be confusing to the users of the palette.
(java`awt`Toolkit`getDefaultToolkit; SetSelectedNotebook[#]) &@ SelectedNotebookas a fix. $\endgroup$
-Djava.awt.headless=trueas an additional argument to the