How to listen to graphic environment or device cha

2019-02-26 10:35发布

问题:

In java one can get the current graphics environment using

GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();

and than loop through the devices using

GraphicsDevice[] screenDevices = graphicsEnvironment.getScreenDevices();

for (int i = 0; i < screenDevices.length; i++) {
    GraphicsDevice graphicsDevice = screenDevices[i];
    ...
}

But the number of GraphicDevices can change at runtime, e.g. by plugging in an USB-monitor. Or the user can change a GraphicsDevice's resolution or move it relative to another graphics device if there are multiple monitors.

How can I listen to changes of the GraphicsEnvironment and the GraphicDevices?

EDIT

I tried to implement the change detection using a daemon thread that inspects the graphics environment at a specific interval, but it doesn't work.

It doesn't work because the GraphicsEnvironment is hold in a statc variable and initialized only once.

Also the sub classes of GraphicsEnvironment cache the GraphicDevices. So new GraphicDevices will only be detected if the jvm process is restarted.

回答1:

A quick and dirty solution would be to batch the execution of an small java program, that just stores the last known graphics environement in a file and execute the notification whenever it changes (execution should be instant, mostly the cost of running the jvm).

It's not elegant, but doing something the native way would need to be cross-platform and would end up ugly too. Unless you don't care about portability.

Choose your poison.