简体   繁体   中英

How to center window in LibGDX with LWJGL3 after resize

I have an undecorated window that needs to be centered, using this configuration:

Lwjgl3ApplicationConfiguration configuration = Lwjgl3ApplicationConfiguration()
configuration.setIdleFPS(60)
configuration.setBackBufferConfig(8,8,8,8,16,0,0)
configuration.setWindowedMode(1920,1080)
configuration.setTitle("Title")
configuration.setDecorated(false)
configuration.setResizable(false)

Later, in app, through options you can change the size of the window with presets defined from a specific aspect ratio. The resizing is made with this call:

Gdx.graphics.setWindowedMode(width, height)

This seems to keep the window in its original top left corner position (which can be at a random position on screen), but I want it to be centered on the monitor, or a way to move the window to any desired position at will.

The question: How can I keep the window created by LibGDX with LWJGL3Application centered when changing window size with SetWindowedMode()

@Tenfour04 stated in response to the old answer below that you can get the LWJGL3Window instance with

Lwjgl3Window window = ((Lwjgl3Graphics)Gdx.graphics).getWindow();

You can then use that to set the position during a resize event for example

window.setWindowPos(x, y)

Old answer:

I solved this by reflection

public void setWindowSize(int width, int height) {
  Lwjgl3Application app = (Lwjgl3Application) Gdx.app
  Field windowfield = app.class.getDeclaredField("currentWindow")
  if(windowfield.trySetAccessible()) {
    Lwjgl3Window window = windowfield.get(app)
    Gdx.graphics.setWindowedMode(width, height)
    // Can use context size because of no decorations on window
    window.setWindowPos(Gdx.graphics.width/2 - width/2, Gdx.graphics.height/2 - height/2)
  }
}

Warning: Even though this works, this is not a good solution. The field of the class is kept private for a reason and not exposing it to the API means that it can change at any update, leaving you with a mess.

That being said, I'm posting this solution for people as desperate as me and because I'm not sure there's another proper solution yet. I will eagerly await a better solution though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM