Georges Oates Larsen
Georges Oates Larsen

Reputation: 7092

Java bring application to front (OSX)

I have been searching all over the internet for this, going from stack overflow answer to stack overflow answer, Trying rococoa, or Class.forName ("com.apple.cocoa.application.NSApplication"); amongst other things.

The bottom line of the matter is, I cannot, for the love of god, figure out how to get my Java application to focus its self on OSX!

Let me be clear: My application has no windows (It will in the future, but sometimes it may not have any windows at all). I need a way to focus my application that does not rely on windows.

Having not found anything, I desperately decided to try a solution that relied on there being a window:

private static void BringSelfToFocus()
{
    java.awt.EventQueue.invokeLater(new Runnable()
    {
        @Override
        public void run()
        {
            Window window = new JFrame("Test");
            window.toFront();
            window.repaint();
        }
    });
}

That, however, like every other futile attempt of mine, failed.

So, yes, while this is technically a duplicate question, I have tried every single other answer I could find, and for whatever reason, none of them worked.

Can anyone please lend a helping hand on this matter? Thankyou.

-Georges

Upvotes: 4

Views: 1486

Answers (1)

Georges Oates Larsen
Georges Oates Larsen

Reputation: 7092

Well! I had one final idea, and it worked! I used Applescript.

private static void BringSelfToFocus()
{
    AppleScript("tell me to activate");
}


private static String AppleScript(String script)
{
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("AppleScript");

    if (engine != null) {
        try
        {
            return (String)engine.eval(script);
        }
        catch (ScriptException e)
        {
            e.printStackTrace();
        }
    }
    return null;
}

Upvotes: 6

Related Questions