I have sucessfully made the components responsive, then get bigger and smaller when the window is stretched. But the problem is whenever the window is resized, the components also gets resized and they look horrible. Hereby I have posted my code. These lines actually scale the components to the size of window:
contentRootRegion.scaleXProperty().bind(scene.widthProperty().divide(origW));
contentRootRegion.scaleYProperty().bind(scene.heightProperty().divide(origH));
Is there an way to make the javafx components responsive and also save their preserved ration or their maximum size? Thank you!
public class ResizingButtons extends Application {
Controller controller;
Scene scene;
Stage stage;
@Override
public void start(Stage stage) throws Exception {
this.stage = stage;
controller = (Controller) replaceSceneContent(
"Test.fxml");
}
public static void main(String[] args) {
launch(args);
}
public Initializable replaceSceneContent(String fxml) throws IOException {
FXMLLoader loader = new FXMLLoader();
InputStream in = this.getClass().getResourceAsStream(fxml);
loader.setBuilderFactory(new JavaFXBuilderFactory());
loader.setLocation(this.getClass().getResource(fxml));
Pane contentRootRegion;
try {
contentRootRegion = (Pane) loader.load();
} finally {
in.close();
}
double origW = 452;
double origH = 526;
if (contentRootRegion.getPrefWidth() == Pane.USE_COMPUTED_SIZE)
contentRootRegion.setPrefWidth(origW);
else
origW = contentRootRegion.getPrefWidth();
if (contentRootRegion.getPrefHeight() == Pane.USE_COMPUTED_SIZE)
contentRootRegion.setPrefHeight(origH);
else
origH = contentRootRegion.getPrefHeight();
// Wrap the resizable content in a non-resizable container (Group)
Group group = new Group(contentRootRegion);
// Place the Group in a StackPane, which will keep it centered
StackPane rootPane = new StackPane();
rootPane.getChildren().add(group);
// Scene scene = new Scene(page);
final Scene scene = new Scene(rootPane, 300, 700);
// Bind the scene's width and height to the scaling parameters on the group
//These two line of codes make the change its height and
// width when the frame is resized
contentRootRegion.scaleXProperty().bind(scene.widthProperty().divide(origW));
contentRootRegion.scaleYProperty().bind(scene.heightProperty().divide(origH));
stage.setScene(scene);
stage.centerOnScreen();
stage.show();
scene.widthProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable,
Number oldValue, Number newValue) {
try {
System.out.println("Scene Width Property is " + scene.getWidth());
System.out.println(controller);
controller.resizeComponents();
} catch (Exception e) {
System.out.println("Error in width listener of scene : " + e.getMessage());
}
}
});
return (Initializable) loader.getController();
}
}