Detect screen resolution change made by user (Java Listener?)

心已入冬 提交于 2019-12-01 15:54:10

This post is old, but: - polling the screen size once every second will not have any impact on performance - when the screen is resized, every window should receive a repaint() call (you need to test this for the OSs you target)

I don't think that Java can do this by itself. You would have to have a "hook" into the operating system that detects this change and may wish to consider using JNA, JNI, or a separate utility such as perhaps Sigar that reports to your Java program. Out of curiosity, why do you wish to do this? Is it for a game you're making or so that you can re-size a GUI application?

Apart from Hovercrafts's suggestion you might consider a background thread that checks the current screen resolution using Toolkit.getScreenSize().

You would need to test this to find out how big the performance impact of that thread to the system is. How often it checks for changes depends on your requirements (how quick your application needs to react to the change)

You can create a global PAINT listener to detect screen resize.

// screen resize listener
    Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {

        @Override
        public void eventDispatched(AWTEvent event) {
// take a look at http://stackoverflow.com/questions/10123735/get-effective-screen-size-from-java
            Rectangle newSize = getEffectiveScreenSize(); 
            if (newSize.width != windowSize.width || newSize.height != windowSize.height)
                resize();

        }
    }, AWTEvent.PAINT_EVENT_MASK);

Here is my suggestion for this problem,

  1. Every swing object can implement an interface called java.awt.event.ComponentListener.
  2. One of its method is componentResized(ComponentEvent e).
  3. Your main application frame should implement this interface and override the resize event method. This is how you listen to the resize event, Checkout this link . I hope this helps you.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!