Change Scene without resize window in JavaFX

后端 未结 2 881
广开言路
广开言路 2020-12-21 10:52

I\'m trying to change Scenes on JavaFX, but without change the window size. However, when I set stage.setScene(scene2); the window size decreases, and I want to

2条回答
  •  温柔的废话
    2020-12-21 11:19

    I have been dealing with an issue similar to yours for the last 4-5 hours and given @James_D's answer I saw the way to simply fix the resizing issue with scene changes. This answer still directly goes off of @James_D, but I did not feel there was a clear explanation as to what was going on, so more than anything I am posting this to help anybody who runs across this thread understand why the second solution @James_D provided (i.e. Changing scenes, not the root of the scene) works.

    Note: I did run across a few answers stating that setting a new root for the scene may be a better option than changing the whole scene, but that did not work in my case, so changing scenes was the best option for me.

    Anyways, I am pretty sure the reason the scene changes sizes when swapped is because you do not set the scene width and height attributes on the scene object explicitly. Not specifically setting the size appears to make the scene adjust to the bounds of the objects it contains automatically when the new scene is loaded to the stage.

    Basically, to fix the problem all you need to do is set the width and height attributes when you create your scene, like below.

    Before

    Scene scene2 = new Scene(root2);
    

    After

    Scene scene2 = new Scene(root2, 900, 600);//or whatever size you want
    stage.setScene(scene2);//now we are set if initial scene is 900w X 600h, scene size will stay the same
    

提交回复
热议问题