Reputation: 31
Currently I display a FileChooser popup in JavaFX upon a button click in the main window. The FileChooser popup appears in the top left corner of the screen. Is there a way to center it in the screen?
FileChooser fileChooser = new FileChooser();
File selectedFile = fileChooser.showOpenDialog(null);
Upvotes: 3
Views: 1944
Reputation: 159341
JavaFX does not expose an API for file chooser positioning.
The following information is Mac specific as I did some testing on a Mac and not Windows. Windows will behave slightly differently, but the recommendation to set the owner of the file chooser still remains in any case.
On a Mac, when you set the owner for the file chooser, which I highly recommend, the internal JavaFX implementation makes it a sheet. To set the owner for the filechooser, pass it to the appropriate show function fileChooser.showOpenDialog(parentStage)
. The default behavior is that the sheet is positioned centered horizontally on the application title bar and positioned directly below the application title bar. When you drag the application title bar around, the sheet moves with it. The internal JavaFX implementation does not publicly expose the sheet positioning API via a Java instance, so there is no way to change where the file chooser sheet is positioned.
The next part I don't recommend: Now, if you don't specify the owner stage in showOpenDialog (e.g. you just pass null
), then the JavaFX Mac implementation will create a modeless dialog centered horizontally on the screen and positioned 100 (non-retina, e.g., JavaFX co-ordinate type) pixels down from the top of the screen. I don't advise doing this though as then the dialog is not window modal (like a sheet is) and doesn't really match up with the application window at all, e.g., you can bring the application window to the front and move it and the file dialog around the screen independent of each other. Also you can shut the application window and the file dialog will still be visible. The user has to shut the file chooser dialog separately, which is kind of buggy behavior.
Upvotes: 2