How to make a swing app aware of screen size change?

眉间皱痕 提交于 2019-12-04 07:18:29

The following worked for me, but I'm on a Mac, so I can't say for sure that it will work on Linux:

System.out.println(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDisplayMode().getWidth() + "x" + GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDisplayMode().getHeight());

//Ignore this block, it was simply to give me a chance to change my resolution
Scanner readUserInput=new Scanner(System.in);
System.out.println("Waiting on input, go change your resolution");
String myName=readUserInput.nextLine();

System.out.println(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDisplayMode().getWidth() + "x" + GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDisplayMode().getHeight());

The output (blah is actually input) was as follows:

1440x900
Waiting on input, go change your resolution
blah
1280x960

Obviously if you have multiple screen devices, you will have to exercise greater caution.

To compute the display size, you can use (taken from GraphicsConfiguration javadoc)

  Rectangle virtualBounds = new Rectangle();
  GraphicsEnvironment ge = GraphicsEnvironment.
          getLocalGraphicsEnvironment();
  GraphicsDevice[] gs =
          ge.getScreenDevices();
  for (int j = 0; j < gs.length; j++) { 
      GraphicsDevice gd = gs[j];
      GraphicsConfiguration[] gc =
          gd.getConfigurations();
      for (int i=0; i < gc.length; i++) {
          virtualBounds =
              virtualBounds.union(gc[i].getBounds());
      }
  } 

You can then query the width and height of virtualBounds.

This will also work in multi-monitor setups.

As far as I know, there is no JDK supported method to detect changes, so polling is your only bet, or use JNA and native code. If your top-level window is maximized, then resizing the display will also resize any maximized windows, so you could listen for changes there also. See this sun tutorial for examples of writing component listeners.

If you don't have a top-level maximized window, then you may also be able to achieve the same effect by creating a hidden maximized window. I can't say for sure if this will work, but it is worth trying.

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

f.setSize(screenSize.width, screenSize.height);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!