How can we prevent the resizing of UI controls in JavaFX?

JavaFXObject Oriented ProgrammingProgramming

In JavaFX the javafx.scene.control package provides various classes for nodes specially designed for UI applications by instantiating these classes you can create UI elements such as button, Label, etc..

You can resize the created elements using the setPrefWidth() or, setPrefHeight() or, setprefSize() methods accordingly.

To prevent the resize of the UI controls you need to set the minimum-maximum and preferred width/height to same value as −

button.setMinWidth(80.0);
button.setPrefWidth(80.0);
button.setMaxWidth(80.0);

Example

The following JavaFX example contains two buttons and a slider. You can resize the button (Hello) by moving the slider. Once you click the PreventResizing button, then you cannot resize the “Hello” button further.

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class PreventingResize extends Application {
   public void start(Stage stage) {
      //Creating a button
      Button button = new Button("Hello");
      //Creating a slider to resize the button
      Slider slider = new Slider(40, 200, 40);
      //Setting its orientation to Horizontal
      slider.setPrefHeight(180);
      slider.setOrientation(Orientation.VERTICAL);
      slider.setShowTickLabels(true);
      slider.setShowTickMarks(true);
      slider.setMajorTickUnit(40);
      slider.setBlockIncrement(20);
      slider.valueProperty().addListener(new ChangeListener<Number>() {
         public void changed(ObservableValue <?extends Number>observable, Number oldValue, Number newValue){
            button.setPrefSize((double)newValue, (double)newValue);
         }
      });
      //Preventing the resize
      Button prevent = new Button("Prevent Resizing");
      //Setting action to the button
      prevent.setOnAction(e -> {
         button.setMinWidth(45);
         button.setPrefWidth(45);
         button.setMaxWidth(45);
         button.setMinHeight(25);
         button.setMaxHeight(25);
         button.setPrefHeight(25);
      });
      //Creating the pane
      BorderPane pane = new BorderPane();
      pane.setCenter(button);
      pane.setRight(prevent);
      pane.setLeft(new VBox(new Label("Button Reize"), slider));
      pane.setPadding(new Insets(10, 10, 10, 10));
      //Preparing the scene
      Scene scene = new Scene(pane, 595, 250);
      stage.setTitle("Preventing Resize");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

raja
Published on 20-May-2020 10:20:49
Advertisements