How to get all Mac OS X window titles from Java

The following getOSWindowTitles() method returns a list of the titles of all open windows in Mac OS X (requires Java 6 and you’ll also need to tick the “Enable access for assistive devices” option in the Universal Access preference page)

public List<String> getOSWindowTitles() throws ScriptException {
    List<String> osWindowTitles = new ArrayList<String>();
    String script = "tell application \"System Events\" to get " + 
        "the title of every window of every process";

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("AppleScript");
    ArrayList<Object> results = (ArrayList<Object>) engine.eval(script);
    for (Object result : flatten(results)) {
        if (result != null) osWindowTitles.add(result.toString());
    return osWindowTitles;

public List<Object> flatten(Collection<Object> nested) {
    ArrayList<Object> flat = new ArrayList<Object>();
    for (Object o : nested) {
        if (o instanceof Collection) {
            flat.addAll(flatten((Collection) o));
        else {
    return flat;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s