How to create a TilePane using JavaFX?

JavaFXObject Oriented ProgrammingProgramming

Once you create all the required nodes for your application you can arrange them using a layout. Where a layout is a process of calculating the position of objects in the given space. JavaFX provides various layouts in the javafx.scene.layout package.

Tile Pane

In this layout, the nodes are arranged as a grid of uniformly sized tiles. You can create a tile pane in your application by instantiating the javafx.scene.layout.TilePane class.

  • On instantiating the TilePane class, by default, a horizontal tile pane will be created, you can change its orientation using the setOrientation() method.

  • You can set the maximum with of the pane using the setMaxWidth() method.

To add nodes to this pane you can either pass them as arguments of the constructor or, add them to the observable list of the pane as −

getChildren().addAll();

Example

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;
public class TilePaneExample extends Application {
   @Override
   public void start(Stage stage) {
      //Creating buttons
      Button one = new Button("one");
      one.setPrefSize(200, 100);
      Button two = new Button("Two");
      two.setPrefSize(200, 100);
      Button three = new Button("Three");
      three.setPrefSize(200, 100);
      Button four = new Button("Four");
      four.setPrefSize(200, 100);
      Button five = new Button("Five");
      five.setPrefSize(200, 100);
      Button six = new Button("six");
      six.setPrefSize(200, 100);
      Button seven = new Button("seven");
      seven.setPrefSize(200, 100);
      Button eight = new Button("eight");
      eight.setPrefSize(200, 100);
      Button nine = new Button("nine");
      nine.setPrefSize(200, 100);
      //Creating the tile pane
      TilePane tilePane = new TilePane();
      //Setting the orientation for the Tile Pane
      tilePane.setOrientation(Orientation.HORIZONTAL);
      //Setting the alignment for the Tile Pane
      tilePane.setTileAlignment(Pos.CENTER_LEFT);
      //Setting the preferred columns for the Tile Pane
      tilePane.setPrefRows(3);
      //Retrieving the observable list of the Tile Pane
      ObservableList list = tilePane.getChildren();
      //Adding the array of buttons to the pane
      list.addAll(one, two, three, four, five, six, seven, eight, nine);
      //Setting the Scene
      Scene scene = new Scene(tilePane, 600, 300);
      stage.setTitle("Tile Pane");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

raja
Published on 19-May-2020 16:44:05
Advertisements