How do you get the screen width in java?

前端 未结 12 699
说谎
说谎 2020-12-13 08:52

Does anyone know how you would get the screen width in java? I read something about some toolkit method but I\'m not quite sure what that is.

Thanks, Andrew

12条回答
  •  忘掉有多难
    2020-12-13 09:29

    The following code should do it (haven't tried it):

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    gd.getDefaultConfiguration().getBounds().getWidth();
    

    edit:

    For multiple monitors you should use the following code (taken from the javadoc of java.awt.GraphicsConfiguration:

      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());
          }
      } 
    

提交回复
热议问题