Wednesday, May 16, 2012

JavaFX 2.0 Layouts: FlowPane

This is the fourth tutorial in JavaFX 2.0 Layout series. It's about FlowPane layout. FlowPane lays out its children in a flow that wraps at the flowpane's boundary. A horizontal flowpane (the default) will layout nodes in rows, wrapping at the flowpane's width. A vertical flowpane lays out nodes in columns, wrapping at the flowpane's height. If the flowpane has a border and/or padding set, the content will be flowed within those insets.
If you still have problems with creating Java project for JavaFX 2.0 in Eclipse IDE, check out Getting Started with JavaFX 2.0 in Eclipse IDE.


FlowPane
FlowPane
In this simple example I will demonstrate how FlowPane layout works.  Above you can see how the program will look in the end of this tutorial.  Below is the code of our example.


Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. import javafx.application.Application;
  2. import javafx.geometry.Insets;
  3. import javafx.scene.Scene;
  4. import javafx.scene.control.Button;
  5. import javafx.scene.layout.FlowPane;
  6. import javafx.stage.Stage;
  7.  
  8. /**
  9.  *
  10.  * @web http://zoranpavlovic.blogspot.com/
  11.  */
  12. public class FlowPaneMain extends Application {
  13.  
  14.     /**
  15.      * @param args the command line arguments
  16.      */
  17.     public static void main(String[] args) {
  18.         launch(args);
  19.     }
  20.      
  21.     @Override
  22.     public void start(Stage primaryStage) {
  23.         primaryStage.setTitle("FlowPane example");
  24.        
  25.         //Adding FlowPane
  26.         FlowPane flowPane = new FlowPane();
  27.         flowPane.setPadding(new Insets(10, 10, 10,10));
  28.         flowPane.setVgap(4);
  29.         flowPane.setHgap(4);
  30.         // preferred width allows for two columns
  31.         flowPane.setPrefWrapLength(210);
  32.                      
  33.         Button btn = new Button();
  34.              
  35.         for(int i=0; i<8; i++){
  36.                    
  37.                 btn = new Button("Button");
  38.                 btn.setPrefSize(100, 50);
  39.                 flowPane.getChildren().add(btn);
  40.            
  41.         }
  42.                
  43.         //Adding FlowPane to the scene
  44.         Scene scene = new Scene(flowPane);
  45.         primaryStage.setScene(scene);
  46.         primaryStage.show();
  47.     }
  48. }


Check other tutorials from JavaFX Layout series by clicking on the image above.
javafx 2 layout



2 comments:

  1. ps: "import javafx.scene.layout.GridPane;" not needed can be removed

    ReplyDelete
  2. Thanks for the feedback.

    Fixed. :)

    ReplyDelete