javawindowsmacosevent-listenerexternal-display

In Java, is it possible to listen for the connection/disconnection of an external Monitor?


Upon disconnecting an external monitor from my laptop, I lose some of my apps as the disconnected monitor is still set as the default. Some of my windows are trying to display on the disconnected monitor.

I have a workaround, such as right clicking on the app icon and selecting move then using the arrow key to move the windows to my laptop. I'm wondering if there is a way in Java to listen for the disconnect, then reset my default screen to my laptop.

I thought about getting the number of and ID's of the screens that are available at startup and adding them to a property file. If a screen is disconnected, get the number of and ID's of the available screens again and compare those values to the values in my property file. I could then set the default to the screen that matches the new values and the stored values.

I haven't started coding this up yet. This is more investigative than anything at this point.


Solution

  • The AWT gives you access to screen information, although "external" is subjective as you might have 2 built-in monitors or 2 external ones.

    At a basic level, you can count the monitors at any moment:

    int numberOfMonitors = 0;
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] gs = ge.getScreenDevices();
    for (int j = 0; j < gs.length; j++) {
        GraphicsDevice gd = gs[j];
        GraphicsConfiguration[] gc = gd.getConfigurations();
        if (gc.getType() == TYPE_RASTER_SCREEN) numberOfMonitors++;
    }
    System.out.println("Number of monitors: " + numberOfMonitors);
    

    To detect the attachment of a new monitor, you will need to poll for the result.

    This is a pure Java solution; to my knowledge if you want anything more accurate than this then you'll probably need to call some native tools on the platform(s) you are targeting. For example, probing sysfs in Linux.