### JavaFX Application Main Class for MVVM Example Source: https://fxdocs.github.io/docs/html5/html5 This Java class defines the main application entry point for a JavaFX MVVM example, extending `javafx.application.Application`. It initializes the primary stage, sets up the scene with a `URLTestView`, and configures basic window properties. The `main` method launches the JavaFX application, demonstrating how to start an MVVM-based UI. ```Java public class ModelChangeApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Scene scene = new Scene(new URLTestView()); primaryStage.setTitle("Model Change App"); primaryStage.setScene( scene ); primaryStage.setWidth(568); primaryStage.setHeight(320); primaryStage.show(); } public static void main(String[] args) { launch(args); } } ``` -------------------------------- ### Setup Core UI Layout Containers Source: https://fxdocs.github.io/docs/html5/html5 Configures the main JavaFX layout using a `VBox` as the root, containing an `HBox` for filter `ToggleButton`s and a `ToggleGroup` to manage their selection behavior. ```Java VBox vbox = new VBox(); vbox.setPadding( new Insets(10)); vbox.setSpacing(4); HBox hbox = new HBox(); hbox.setSpacing( 2 ); ToggleGroup filterTG = new ToggleGroup(); ``` -------------------------------- ### Initialize JavaFX TilePane with 3x3 grid and colored rectangles Source: https://fxdocs.github.io/docs/html5/html5 This JavaFX application demonstrates the basic setup of a `TilePane`. It creates a 3x3 grid, adds nine `Rectangle` objects of various colors, and centers them within their tiles using `setTileAlignment(Pos.CENTER)`. This example illustrates how to populate a `TilePane` with child nodes. ```java public class ThreeByThreeApp extends Application { @Override public void start(Stage primaryStage) throws Exception { TilePane tilePane = new TilePane(); tilePane.setPrefColumns(3); tilePane.setPrefRows(3); tilePane.setTileAlignment( Pos.CENTER ); tilePane.getChildren().addAll( new Rectangle(50, 50, Color.RED), new Rectangle( 50, 50, Color.GREEN ), new Rectangle( 50, 50, Color.BLUE ), new Rectangle( 50, 50, Color.YELLOW ), new Rectangle( 50, 50, Color.CYAN ), new Rectangle( 50, 50, Color.PURPLE ), new Rectangle( 50, 50, Color.BROWN ), new Rectangle( 50, 50, Color.PINK ), new Rectangle( 50, 50, Color.ORANGE ) ); Scene scene = new Scene(tilePane); scene.setFill(Color.LIGHTGRAY); primaryStage.setTitle("3x3"); primaryStage.setScene( scene ); primaryStage.show(); } public static void main(String[] args) {launch(args);} } ``` -------------------------------- ### JavaFX Application Setup for Dialog Display Source: https://fxdocs.github.io/docs/html5/html5 This snippet defines the main `DialogApp` class, extending `Application`. It sets up the primary stage with a `TextField` for a database URL and a 'Set' `Button` that triggers the dialog display. It also includes the standard `main` method to launch the JavaFX application. ```Java public class DialogApp extends Application { private final TextField dbURL = new TextField(); @Override public void start(Stage primaryStage) throws Exception { Label label = new Label("DB URL"); dbURL.setPrefWidth(400.0d ); Button btn = new Button("Set"); btn.setOnAction( this::showSetDialog ); VBox vbox = new VBox(label, dbURL, btn ); vbox.setSpacing( 10.0d ); vbox.setPadding( new Insets(40.0d) ); Scene scene = new Scene( vbox ); primaryStage.setTitle("Dialog App"); primaryStage.setScene( scene ); primaryStage.show(); } public static void main(String[] args) { launch(args); } ``` -------------------------------- ### JavaFX: Base Application for Node Transformations Source: https://fxdocs.github.io/docs/html5/html5 This JavaFX application provides a foundational setup for demonstrating various node transformations. It creates a `Stage` and `Scene`, then adds a blue `Rectangle` to the scene. The `transform` method is included as a placeholder where specific transformation logic will be applied in subsequent examples. ```Java public class TransformApp extends Application { private Parent createContent() { Rectangle box = new Rectangle(100, 50, Color.BLUE); transform(box); return new Pane(box); } private void transform(Rectangle box) { // we will apply transformations here } @Override public void start(Stage stage) throws Exception { stage.setScene(new Scene(createContent(), 300, 300, Color.GRAY)); stage.show(); } public static void main(String[] args) { launch(args); } } ``` -------------------------------- ### JavaFX TilePane Application Example Source: https://fxdocs.github.io/docs/html5/html5 Demonstrates a complete JavaFX application using TilePane to arrange interactive circles. It includes features for selecting circles, changing their opacity, and shuffling their order on key press. ```Java public class TileApp extends Application { @Override public void start(Stage primaryStage) throws Exception { TilePane tilePane = new TilePane(); tilePane.setPrefColumns(2); tilePane.setPrefRows(2); tilePane.setTileAlignment( Pos.CENTER ); Circle redCircle = new Circle(50, Color.RED); Circle greenCircle = new Circle( 50, Color.GREEN ); Circle blueCircle = new Circle( 50, Color.BLUE ); Circle yellowCircle = new Circle( 50, Color.YELLOW ); List circles = new ArrayList<>(); circles.add( redCircle ); circles.add( greenCircle ); circles.add( blueCircle ); circles.add( yellowCircle ); circles .stream() .forEach( (c) -> c.getProperties().put( "selected", Boolean.FALSE )); tilePane.getChildren().addAll( circles ); tilePane.setOnMouseClicked( (evt) -> tilePane .getChildren() .stream() .filter( c -> c.contains( c.sceneToLocal(evt.getSceneX(), evt.getSceneY(), true) ) ) .findFirst() .ifPresent( (c) -> { Boolean selected = (Boolean) c.getProperties().get("selected"); if( selected == null || selected == Boolean.FALSE ) { c.setOpacity(0.3d); c.getProperties().put("selected", Boolean.TRUE); } else { c.setOpacity( 1.0d ); c.getProperties().put("selected", Boolean.FALSE); } } ) ); Scene scene = new Scene(tilePane); scene.setOnKeyPressed( (evt) -> { if( evt.getCode().equals(KeyCode.S) ) { Collections.shuffle( circles ); tilePane.getChildren().clear(); tilePane.getChildren().addAll( circles ); } } ); primaryStage.setTitle("TileApp"); primaryStage.setScene( scene ); primaryStage.show(); } public static void main(String[] args) { launch(args); } } ``` -------------------------------- ### JavaFX ChoiceBox Application Setup Source: https://fxdocs.github.io/docs/html5/html5 This code sets up a basic JavaFX application (`ChoicesApp`) demonstrating the use of `ChoiceBox`, `Label`, `Button`, and `HBox`. It initializes the UI elements, arranges them in a horizontal box, and sets an action listener for the save button to print the selected value. The `ChoiceBox` is designed to hold `Pair` objects. ```Java public class ChoicesApp extends Application { private final ChoiceBox> assetClass = new ChoiceBox<>(); @Override public void start(Stage primaryStage) throws Exception { Label label = new Label("Asset Class:"); assetClass.setPrefWidth(200); Button saveButton = new Button("Save"); HBox hbox = new HBox( label, assetClass, saveButton); hbox.setSpacing( 10.0d ); hbox.setAlignment(Pos.CENTER ); hbox.setPadding( new Insets(40) ); Scene scene = new Scene(hbox); initChoice(); saveButton.setOnAction( (evt) -> System.out.println("saving " + assetClass.getValue()) ); primaryStage.setTitle("ChoicesApp"); primaryStage.setScene( scene ); primaryStage.show(); } ``` -------------------------------- ### JavaFX: Complete TitledPane Application Example Source: https://fxdocs.github.io/docs/html5/html5 This comprehensive JavaFX application (`TitledPaneApp`) showcases the full implementation of a UI using `TitledPane`. It demonstrates creating a basic search interface with expandable 'Advanced' options, setting initial expansion state, and integrating UI components within `VBox` layouts. ```java public class TitledPaneApp extends Application { @Override public void start(Stage primaryStage) throws Exception { VBox vbox = new VBox( new Label("Keywords" ), new TextField() ); vbox.setPadding( new Insets(10) ); vbox.setSpacing( 10 ); VBox advancedVBox = new VBox( new Label("All Keywords"), new CheckBox(), new Label("Domains"), new TextField(), new Label("Time"), new ComboBox( FXCollections.observableArrayList( "Day", "Month", "Year" ) ) ); TitledPane titledPane = new TitledPane( "Advanced", advancedVBox ); titledPane.setExpanded( false ); vbox.getChildren().addAll( titledPane, new Button("Search") ); Scene scene = new Scene( vbox ); primaryStage.setTitle( "TitledPaneApp" ); primaryStage.setScene( scene ); primaryStage.setWidth( 568 ); primaryStage.setHeight( 320 ); primaryStage.show(); } public static void main(String[] args) { launch(args); } } ``` -------------------------------- ### JavaFX ComboBox Application Example Source: https://fxdocs.github.io/docs/html5/html5 A complete JavaFX application demonstrating the use of `ComboBox` with custom `Pair` objects. It shows how to populate the ComboBox, set a custom cell factory for display, and handle save actions based on the selected item. ```java public class CombosApp extends Application { private final ComboBox> account = new ComboBox<>(); private final static Pair EMPTY_PAIR = new Pair<>("", ""); @Override public void start(Stage primaryStage) throws Exception { Label accountsLabel = new Label("Account:"); account.setPrefWidth(200); Button saveButton = new Button("Save"); HBox hbox = new HBox( accountsLabel, account, saveButton); hbox.setSpacing( 10.0d ); hbox.setAlignment(Pos.CENTER ); hbox.setPadding( new Insets(40) ); Scene scene = new Scene(hbox); initCombo(); saveButton.setOnAction( (evt) -> { if( account.getValue().equals(EMPTY_PAIR ) ) { System.out.println("no save needed; no item selected"); } else { System.out.println("saving " + account.getValue()); } }); primaryStage.setTitle("CombosApp"); primaryStage.setScene( scene ); primaryStage.show(); } private void initCombo() { List> accounts = new ArrayList<>(); accounts.add( new Pair<>("Auto Expense", "60000") ); accounts.add( new Pair<>("Interest Expense", "61000") ); accounts.add( new Pair<>("Office Expense", "62000") ); accounts.add( new Pair<>("Salaries Expense", "63000") ); account.getItems().add( EMPTY_PAIR ); account.getItems().addAll( accounts ); account.setValue( EMPTY_PAIR ); Callback>, ListCell>> factory = (lv) -> new ListCell>() { @Override protected void updateItem(Pair item, boolean empty) { super.updateItem(item, empty); if( empty ) { setText(""); } else { setText( item.getKey() ); } } }; account.setCellFactory( factory ); account.setButtonCell( factory.call( null ) ); } public static void main(String[] args) { launch(args); } } ``` -------------------------------- ### Complete JavaFX Application: NoNullComboApp Source: https://fxdocs.github.io/docs/html5/html5 This is the full source code for the `NoNullComboApp` demonstrating how to initialize `ComboBox`es with an 'empty' selection, populate them with data, and handle user interactions to prevent null values. It includes UI setup, data initialization, and event handling for country-city filtering and saving. ```Java public class NoNullComboApp extends Application { private final ComboBox country = new ComboBox<>(); private final ComboBox city = new ComboBox<>(); private List countries = new ArrayList<>(); private Map> citiesMap = new LinkedHashMap<>(); @Override public void start(Stage primaryStage) throws Exception { Label countryLabel = new Label("Country:"); country.setPrefWidth(200.0d); Label cityLabel = new Label("City:"); city.setPrefWidth(200.0d); Button saveButton = new Button("Save"); VBox vbox = new VBox( countryLabel, country, cityLabel, city, saveButton ); vbox.setAlignment(Pos.CENTER_LEFT ); vbox.setSpacing( 10.0d ); TilePane outerBox = new TilePane(vbox); outerBox.setAlignment(Pos.CENTER); Scene scene = new Scene(outerBox); initData(); country.getItems().add(""); country.getItems().addAll( countries ); country.setValue( "" ); // empty selection is object and not null city.getItems().add(""); city.setValue( "" ); country.setOnAction( (evt) -> { String cty = country.getValue(); city.getItems().removeIf( (c) -> !c.isEmpty() ); if( citiesMap.containsKey(cty) ) { // not an empty key city.getItems().addAll( citiesMap.get(cty) ); } }); saveButton.setOnAction( (evt) -> { System.out.println("saving country='" + country.getValue() + "', city='" + city.getValue() + "'"); }); primaryStage.setTitle("NoNullComboApp"); primaryStage.setScene( scene ); primaryStage.setWidth( 320 ); primaryStage.setHeight( 480 ); primaryStage.show(); } public static void main(String[] args) { launch(args); } private void initData() { String COUNTRY_FR = "France"; String COUNTRY_DE = "Germany"; String COUNTRY_CH = "Switzerland"; countries.add(COUNTRY_FR); countries.add(COUNTRY_DE); countries.add(COUNTRY_CH); List frenchCities = new ArrayList<>(); frenchCities.add("Paris"); frenchCities.add("Strasbourg"); List germanCities = new ArrayList<>(); germanCities.add("Berlin"); germanCities.add("Cologne"); germanCities.add("Munich"); List swissCities = new ArrayList<>(); swissCities.add("Zurich"); citiesMap.put(COUNTRY_FR, frenchCities ); citiesMap.put(COUNTRY_DE, germanCities ); citiesMap.put(COUNTRY_CH, swissCities ); } } ``` -------------------------------- ### Create EmploymentRequestModel for Data Persistence Source: https://fxdocs.github.io/docs/html5/html5 This Model class handles the persistence of data. In this example, it includes a mocked `save` method to demonstrate receiving and processing `EmploymentRequest` data. ```java public class EmploymentRequestModel { public void save(EmploymentRequest req) { System.out.println("saving " + req); } } ``` -------------------------------- ### Initialize JavaFX UI Layout in start() Method Source: https://fxdocs.github.io/docs/html5/html5 This code initializes the primary stage of the JavaFX application. It creates a `GridPane` to arrange `Label` and `TextField` components for track information, setting horizontal and vertical gaps for proper spacing. It also configures the `GridPane` to grow vertically and applies a margin. ```Java @Override public void start(Stage primaryStage) throws Exception { GridPane gp = new GridPane(); gp.add(new Label("Artist"), 0, 0); gp.add(tfArtist, 1, 0); gp.add(new Label("Album"), 0, 1); gp.add(tfAlbum, 1, 1); gp.add(new Label("Track"), 0, 2); gp.add(tfTrack, 1, 2); gp.add(new Label("#"), 0, 3); gp.add(tfTrackNo, 1, 3); gp.add(new Label("Rating"), 0, 4); gp.add(tfRating, 1, 4); gp.add(new Label("Downloaded"), 0, 5); gp.add(tfDownloaded, 1, 5); gp.setHgap(4.0d); gp.setVgap(8.0d); VBox.setVgrow(gp, Priority.ALWAYS); VBox.setMargin( gp, new Insets(40.0d) ); ``` -------------------------------- ### Initialize JavaFX AnchorPane and Scene Source: https://fxdocs.github.io/docs/html5/html5 This snippet demonstrates the basic setup for a JavaFX application using an AnchorPane as the root layout container. An AnchorPane object is created and then assigned to a Scene, which is the container for all content in a scene graph. ```Java AnchorPane ap = new AnchorPane(); Scene scene = new Scene(ap); ``` -------------------------------- ### JavaFX: Simplifying StyleableProperty and CssMetaData with StyleablePropertyFactory Source: https://fxdocs.github.io/docs/html5/html5 Illustrates how to use StyleablePropertyFactory to streamline the creation of StyleableProperty and CssMetaData in JavaFX. This example shows how the factory simplifies defining CSS properties like color, reducing boilerplate code compared to manual implementation, and how to retrieve the combined CSS metadata for the control. ```Java // StyleableProperty private final StyleableProperty color = new SimpleStyleableObjectProperty<>(COLOR, this, "color"); // Typical JavaFX property implementation public Color getColor() { return this.color.getValue(); } public void setColor(final Color color) { this.color.setValue(color); } public ObjectProperty colorProperty() { return (ObjectProperty) this.color; } // StyleablePropertyFactory private static final StyleablePropertyFactory FACTORY = new StyleablePropertyFactory<>(Control.getClassCssMetaData()); // CssMetaData from StyleablePropertyFactory private static final CssMetaData COLOR = FACTORY.createColorCssMetaData("-color", s -> s.color, Color.RED, false); // Return all CssMetadata information from StyleablePropertyFactory public static List> getClassCssMetaData() { return FACTORY.getCssMetaData(); } @Override public List> getControlCssMetaData() { return getClassCssMetaData(); } ``` -------------------------------- ### JavaFX MVVM View UI Layout and Event Handlers Setup Source: https://fxdocs.github.io/docs/html5/html5 This snippet illustrates the `createView()` method, which programmatically constructs the user interface. It arranges UI elements using `GridPane` and `VBox` for layout, sets up column constraints, and attaches action event handlers to the buttons, delegating the actual logic to private methods within the View. ```Java private void createView() { VBox gpwrap = new VBox(); gpwrap.setAlignment( Pos.CENTER ); gp.setPadding( new Insets(40) ); gp.setVgap( 4 ); gp.add(new Label("Name"), 0, 0); gp.add(tfName, 1, 0); gp.add(new Label("Desired Position"), 0, 1); gp.add(tfPosition, 1, 1); gp.add(new Label("Current Annual Salary"), 0, 2); gp.add(tfAnnualSalary, 1, 2); final ColumnConstraints col = new ColumnConstraints(); col.setPercentWidth( 50 ); gp.getColumnConstraints().addAll( col, col ); gpwrap.getChildren().add( gp ); VBox.setVgrow( gpwrap, Priority.ALWAYS ); btnSave.setOnAction( this::save ); btnCancel.setOnAction( this::cancel ); btnReset.setOnAction( this::reset ); btnSave.setDefaultButton(true); ButtonBar buttonBar = new ButtonBar(); buttonBar.setPadding( new Insets(20.0d) ); ButtonBar.setButtonData(btnSave, ButtonBar.ButtonData.OK_DONE); ButtonBar.setButtonData(btnCancel, ButtonBar.ButtonData.CANCEL_CLOSE); ButtonBar.setButtonData(btnReset, ButtonBar.ButtonData.OTHER); buttonBar.getButtons().addAll( btnSave, btnCancel, btnReset ); this.getChildren().addAll( gpwrap, new Separator(), buttonBar); } ``` -------------------------------- ### Initialize Player Data Properties Source: https://fxdocs.github.io/docs/html5/html5 Initializes `playersProperty` as an `ObservableList` to hold all player objects and `viewablePlayersProperty` as a `FilteredList` derived from `playersProperty`. This setup ensures that changes to the base list are reflected in the viewable list, which can then be filtered. ```Java ReadOnlyObjectProperty> playersProperty = new SimpleObjectProperty<>(FXCollections.observableArrayList()); ReadOnlyObjectProperty> viewablePlayersProperty = new SimpleObjectProperty>( new FilteredList<>(playersProperty.get() )); ``` -------------------------------- ### Full JavaFX Pane Application with Absolute Positioning Source: https://fxdocs.github.io/docs/html5/html5 This complete JavaFX `Application` subclass (`PaneApp`) showcases a comprehensive UI built using a `Pane` for absolute positioning of various `Shape` objects like `Arc` and `Circle`, along with a `Hyperlink`. It demonstrates setting up a `VBox` as the root, applying background styles, creating and configuring multiple UI elements, managing their z-order by addition sequence, and dynamically adjusting a `Hyperlink`'s position upon stage display. This example provides a holistic view of building a simple JavaFX application with manual layout control. ```Java public class PaneApp extends Application { @Override public void start(Stage primaryStage) throws Exception { VBox vbox = new VBox(); vbox.setPadding( new Insets( 10 ) ); vbox.setBackground( new Background( new BackgroundFill(Color.BLACK, new CornerRadii(0), new Insets(0)) )); Pane p = new Pane(); Arc largeArc = new Arc(0, 0, 100, 100, 270, 90); largeArc.setFill(Color.web("0x59291E")); largeArc.setType(ArcType.ROUND); Arc backgroundArc = new Arc(0, 0, 160, 160, 270, 90 ); backgroundArc.setFill( Color.web("0xD96F32") ); backgroundArc.setType( ArcType.ROUND ); Arc smArc1 = new Arc( 0, 160, 30, 30, 270, 180); smArc1.setFill(Color.web("0xF2A444")); smArc1.setType(ArcType.ROUND); Circle smCircle = new Circle( 160/Math.sqrt(2.0), 160/Math.sqrt(2.0), 30,Color.web("0xF2A444") ); Arc smArc2 = new Arc( 160, 0, 30, 30, 180, 180); smArc2.setFill(Color.web("0xF2A444")); smArc2.setType(ArcType.ROUND); Hyperlink hyperlink = new Hyperlink("About this App"); hyperlink.setFont( Font.font(36) ); hyperlink.setTextFill( Color.web("0x3E6C93") ); hyperlink.setBorder( Border.EMPTY ); Arc medArc = new Arc(568-20, 320-20, 60, 60, 90, 90); medArc.setFill(Color.web("0xD9583B")); medArc.setType(ArcType.ROUND); p.getChildren().addAll( backgroundArc, largeArc, smArc1, smCircle, smArc2, hyperlink, medArc ); vbox.getChildren().add( p ); Scene scene = new Scene(vbox); scene.setFill(Color.BLACK); primaryStage.setTitle("Pane App"); primaryStage.setScene( scene ); primaryStage.setWidth( 568 ); primaryStage.setHeight( 320 ); primaryStage.setOnShown( (evt) -> { hyperlink.setLayoutX( 284 - (hyperlink.getWidth()/3) ); hyperlink.setLayoutY( 160 - hyperlink.getHeight() ); }); primaryStage.show(); } public static void main(String[] args) { launch(args); } } ``` -------------------------------- ### Java: Initialize Country and City Data for NoNullComboApp Source: https://fxdocs.github.io/docs/html5/html5 This Java code defines and populates the core data structures for the application: a List of country names and a Map associating countries with their respective city lists. This setup ensures the application has pre-defined data for its UI components. ```java public class NoNullComboApp extends Application { private List countries = new ArrayList<>(); private Map> citiesMap = new LinkedHashMap<>(); private void initData() { String COUNTRY_FR = "France"; String COUNTRY_DE = "Germany"; String COUNTRY_CH = "Switzerland"; countries.add(COUNTRY_FR); countries.add(COUNTRY_DE); countries.add(COUNTRY_CH); List frenchCities = new ArrayList<>(); frenchCities.add("Paris"); frenchCities.add("Strasbourg"); List germanCities = new ArrayList<>(); germanCities.add("Berlin"); germanCities.add("Cologne"); germanCities.add("Munich"); List swissCities = new ArrayList<>(); swissCities.add("Zurich"); citiesMap.put(COUNTRY_FR, frenchCities ); citiesMap.put(COUNTRY_DE, germanCities ); citiesMap.put(COUNTRY_CH, swissCities ); } ``` -------------------------------- ### Complete JavaFX Support Ticket Application with GridPane and ButtonBar Source: https://fxdocs.github.io/docs/html5/html5 This comprehensive JavaFX example presents a `GridPaneApp` class that extends `Application`. It constructs a user interface for a support ticket form, utilizing `GridPane` for precise element alignment (labels, text fields, combo box, text area) and a `ButtonBar` for 'Save' and 'Cancel' actions. The code demonstrates setting padding, gaps, and integrating `ButtonBar` within a `VBox`. ```Java public class GridPaneApp extends Application { @Override public void start(Stage primaryStage) throws Exception { VBox vbox = new VBox(); GridPane gp = new GridPane(); gp.setPadding( new Insets(10) ); gp.setHgap( 4 ); gp.setVgap( 8 ); VBox.setVgrow(gp, Priority.ALWAYS ); Label lblTitle = new Label("Support Ticket"); Label lblEmail = new Label("Email"); TextField tfEmail = new TextField(); Label lblPriority = new Label("Priority"); ObservableList priorities = FXCollections.observableArrayList("Medium", "High", "Low"); ComboBox cbPriority = new ComboBox<>(priorities); Label lblProblem = new Label("Problem"); TextField tfProblem = new TextField(); Label lblDescription = new Label("Description"); TextArea taDescription = new TextArea(); gp.add( lblTitle, 1, 1); // empty item at 0,0 gp.add( lblEmail, 0, 2); gp.add(tfEmail, 1, 2); gp.add( lblPriority, 0, 3); gp.add( cbPriority, 1, 3); gp.add( lblProblem, 0, 4); gp.add( tfProblem, 1, 4); gp.add( lblDescription, 0, 5); gp.add( taDescription, 1, 5); Separator sep = new Separator(); // hr ButtonBar buttonBar = new ButtonBar(); buttonBar.setPadding( new Insets(10) ); Button saveButton = new Button("Save"); Button cancelButton = new Button("Cancel"); buttonBar.setButtonData(saveButton, ButtonBar.ButtonData.OK_DONE); buttonBar.setButtonData(cancelButton, ButtonBar.ButtonData.CANCEL_CLOSE); buttonBar.getButtons().addAll(saveButton, cancelButton); vbox.getChildren().addAll( gp, sep, buttonBar ); Scene scene = new Scene(vbox); primaryStage.setTitle("Grid Pane App"); primaryStage.setScene(scene); primaryStage.setWidth( 736 ); primaryStage.setHeight( 414 ); primaryStage.show(); } public static void main(String[] args) { launch(args); } } ``` -------------------------------- ### JavaFX TableView Application Example Source: https://fxdocs.github.io/docs/html5/html5 This JavaFX application demonstrates how to create a TableView to display a list of Item objects. It sets up columns with PropertyValueFactory, populates initial data, and includes two buttons (Inventory, Tax) whose disabled states are dynamically bound to the TableView's selection model, showcasing conditional UI interaction. The layout uses VBox and HBox. ```java public class TableSelectApp extends Application { @Override public void start(Stage primaryStage) throws Exception { TableView tblItems = new TableView<>(); tblItems.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); VBox.setVgrow(tblItems, Priority.ALWAYS ); TableColumn colSKU = new TableColumn<>("SKU"); TableColumn colDescr = new TableColumn<>("Item"); TableColumn colPrice = new TableColumn<>("Price"); TableColumn colTaxable = new TableColumn<>("Tax"); colSKU.setCellValueFactory( new PropertyValueFactory<>("sku") ); colDescr.setCellValueFactory( new PropertyValueFactory<>("descr") ); colPrice.setCellValueFactory( new PropertyValueFactory<>("price") ); colTaxable.setCellValueFactory( new PropertyValueFactory<>("taxable") ); tblItems.getColumns().addAll( colSKU, colDescr, colPrice, colTaxable ); tblItems.getItems().addAll( new Item("KBD-0455892", "Mechanical Keyboard", 100.0f, true), new Item( "145256", "Product Docs", 0.0f, false ), new Item( "OR-198975", "O-Ring (100)", 10.0f, true) ); Button btnInventory = new Button("Inventory"); Button btnCalcTax = new Button("Tax"); btnInventory.disableProperty().bind( tblItems.getSelectionModel().selectedItemProperty().isNull() ); btnCalcTax.disableProperty().bind( tblItems.getSelectionModel().selectedItemProperty().isNull().or( Bindings.select( tblItems.getSelectionModel().selectedItemProperty(), "taxable" ).isEqualTo(false) ) ); HBox buttonHBox = new HBox( btnInventory, btnCalcTax ); buttonHBox.setSpacing( 8 ); VBox vbox = new VBox( tblItems, buttonHBox ); vbox.setPadding( new Insets(10) ); vbox.setSpacing( 10 ); Scene scene = new Scene(vbox); primaryStage.setTitle("TableSelectApp"); primaryStage.setScene( scene ); primaryStage.setHeight( 376 ); primaryStage.setWidth( 667 ); primaryStage.show(); } public static void main(String[] args) { launch(args); } } ``` -------------------------------- ### JavaFX: Manual Implementation of StyleableProperty and CssMetaData Source: https://fxdocs.github.io/docs/html5/html5 Demonstrates the manual setup of a StyleableProperty for a custom JavaFX control, including its getter, setter, and property accessor methods. It also shows how to define and integrate CssMetaData to enable CSS styling for the property, overriding isSettable and getStyleableProperty methods, and combining with ancestor CSS metadata. ```Java // StyleableProperty private final StyleableProperty color = new SimpleStyleableObjectProperty<>(COLOR, this, "color"); // Typical JavaFX property implementation public Color getColor() { return this.color.getValue(); } public void setColor(final Color color) { this.color.setValue(color); } public ObjectProperty colorProperty() { return (ObjectProperty) this.color; } // CssMetaData private static final CssMetaData COLOR = new CssMetaData("-color", PaintConverter.getInstance(), Color.RED) { @Override public boolean isSettable(MY_CTRL node) { return node.color == null || !node.color.isBound(); } @Override public StyleableProperty getStyleableProperty(MY_CTRL node) { return node.color; } }; private static final List> STYLEABLES; static { // Fetch CssMetaData from its ancestors final List> styleables = new ArrayList<>(Control.getClassCssMetaData()); // Add new CssMetaData styleables.add(COLOR); STYLEABLES = Collections.unmodifiableList(styleables); } // Return all CssMetadata information public static List> getClassCssMetaData() { return STYLEABLES; } @Override public List> getControlCssMetaData() { return getClassCssMetaData(); } ``` -------------------------------- ### JavaFX: Configure UI Layout for NoNullComboApp Source: https://fxdocs.github.io/docs/html5/html5 This JavaFX code snippet, part of the start method, illustrates the construction of the application's user interface. It arranges Label, ComboBox, and Button components within a VBox for vertical alignment, which is then centered on the screen using a TilePane to prevent stretching. ```java @Override public void start(Stage primaryStage) throws Exception { Label countryLabel = new Label("Country:"); country.setPrefWidth(200.0d); Label cityLabel = new Label("City:"); city.setPrefWidth(200.0d); Button saveButton = new Button("Save"); VBox vbox = new VBox( countryLabel, country, cityLabel, city, saveButton ); vbox.setAlignment(Pos.CENTER_LEFT ); vbox.setSpacing( 10.0d ); TilePane outerBox = new TilePane(vbox); outerBox.setAlignment(Pos.CENTER); Scene scene = new Scene(outerBox); initData(); ``` -------------------------------- ### JavaFX Application Demonstrating Screen Dimensions Before and After OnShown Event Source: https://fxdocs.github.io/docs/html5/html5 This JavaFX application illustrates the timing difference in screen geometry availability. It displays the primary stage's width and height at two points: immediately after setScene() (before show()) and within an onShown event handler. The example demonstrates that dimensions are NaN before the stage is shown and valid numerical values after the onShown event fires. ```Java public class StartVsShownJavaFXApp extends Application { private DoubleProperty startX = new SimpleDoubleProperty(); private DoubleProperty startY = new SimpleDoubleProperty(); private DoubleProperty shownX = new SimpleDoubleProperty(); private DoubleProperty shownY = new SimpleDoubleProperty(); @Override public void start(Stage primaryStage) throws Exception { Label startLabel = new Label("Start Dimensions"); TextField startTF = new TextField(); startTF.textProperty().bind( Bindings.format("(%.1f, %.1f)", startX, startY) ); Label shownLabel = new Label("Shown Dimensions"); TextField shownTF = new TextField(); shownTF.textProperty().bind( Bindings.format("(%.1f, %.1f)", shownX, shownY) ); GridPane gp = new GridPane(); gp.add( startLabel, 0, 0 ); gp.add( startTF, 1, 0 ); gp.add( shownLabel, 0, 1 ); gp.add( shownTF, 1, 1 ); gp.setHgap(10); gp.setVgap(10); HBox hbox = new HBox(gp); hbox.setAlignment(CENTER); VBox vbox = new VBox(hbox); vbox.setAlignment(CENTER); Scene scene = new Scene( vbox, 480, 320 ); primaryStage.setScene( scene ); // before show()...I just set this to 480x320, right? startX.set( primaryStage.getWidth() ); startY.set( primaryStage.getHeight() ); primaryStage.setOnShown( (evt) -> { shownX.set( primaryStage.getWidth() ); shownY.set( primaryStage.getHeight() ); // all available now }); primaryStage.setTitle("Start Vs. Shown"); primaryStage.show(); } public static void main(String[] args) { launch(args); } } ``` -------------------------------- ### JavaFX: Basic 'Hello World' Scene Graph Application Source: https://fxdocs.github.io/docs/html5/html5 This JavaFX application demonstrates the fundamental structure of a scene graph. It initializes a `Stage` as the primary window, attaches a `Scene` to it, and populates the scene with a `StackPane` containing a 'Hello World' `Text` node. This showcases how to set up a simple JavaFX UI. ```Java public class HelloApp extends Application { private Parent createContent() { return new StackPane(new Text("Hello World")); } @Override public void start(Stage stage) throws Exception { stage.setScene(new Scene(createContent(), 300, 300)); stage.show(); } public static void main(String[] args) { launch(args); } } ``` -------------------------------- ### Define URLTestModel for HTTP GET Requests and Notifications Source: https://fxdocs.github.io/docs/html5/html5 This Java class, `URLTestModel`, is responsible for executing HTTP GET requests to a specified URL. It maintains an `Optional` `URLTestObject` to store the results, including status code, elapsed time, or error details. Upon completion, it publishes an update notification via a `Notifications` object, enabling decoupled updates for ViewModels without holding direct references. ```Java public class URLTestModel { private final Notifications notifications = new Notifications(); private Optional urlTestObject = Optional.empty(); public Optional getUrlTestObject() { return urlTestObject; } public Optional testURL(String url) { try { long startTimeMillis = System.currentTimeMillis(); HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection(); try ( InputStream is = urlConnection.getInputStream(); ) { while (is.read() != -1) { } } long endTimeMillis = System.currentTimeMillis(); URLTestObject uto = new URLTestObject( urlConnection.getResponseCode(), (int) (endTimeMillis - startTimeMillis) ); urlTestObject = Optional.of(uto); } catch(Exception exc) { URLTestObject uto = new URLTestObject(exc.getMessage()); urlTestObject = Optional.of(uto); } notifications.publish(Notifications.EVENT_MODEL_UPDATE); return urlTestObject; } } ``` -------------------------------- ### Initialize Application with Track POJO Data in JavaFX Source: https://fxdocs.github.io/docs/html5/html5 Illustrates the initialization of the `BindingsSelectApp` JavaFX application with a `currentTrack` instance. This snippet shows how a `Track` POJO is instantiated with sample data, serving as the model for UI binding demonstrations. ```Java public class BindingsSelectApp extends Application { private final Track currentTrack = new Track( "Jaco Pastorious", "Jaco Pastorious", "Come On, Come Over", 2, new Rating(4.99f, 5.00f), false ); ``` -------------------------------- ### Initialize URLTestViewModel with Collaborators and Subscriptions (Java) Source: https://fxdocs.github.io/docs/html5/html5 This Java code demonstrates the constructor of `URLTestViewModel`, showing how it initializes `URLTestModel` and `Notifications` objects. It also illustrates how the ViewModel subscribes to `Notifications.EVENT_MODEL_UPDATE` to trigger an `update` method call upon receiving the notification. ```Java private final URLTestModel urlTestModel = new URLTestModel(); private final Notifications notifications = new Notifications(); public URLTestViewModel() { notifications.subscribe(Notifications.EVENT_MODEL_UPDATE, this, this::update); // presented later } ``` -------------------------------- ### Anchor JavaFX Label to Bottom-Left Source: https://fxdocs.github.io/docs/html5/html5 This example demonstrates anchoring a simple Label control to the bottom-left corner of the AnchorPane. Similar to other anchored elements, it maintains its position relative to the specified edges with a defined offset. ```Java Label statusLabel = new Label("Program status"); ap.getChildren().add( statusLabel ); AnchorPane.setBottomAnchor( statusLabel, 10.0d ); AnchorPane.setLeftAnchor( statusLabel, 10.0d ); ``` -------------------------------- ### JavaFX Image Class Constructors Source: https://fxdocs.github.io/docs/html5/html5 Demonstrates various constructors for the JavaFX `Image` class, showing how to load images from a URL with specified dimensions and aspect ratio preservation. It highlights loading from classpath-relative or absolute URLs. ```java public class ImageApp extends Application { private final static String IMAGE_LOC = "images/keyboard.jpg"; @Override public void start(Stage primaryStage) throws Exception { Image image2 = new Image(IMAGE_LOC, 360.0d, 360.0d, true, true ); Image image3 = new Image(IMAGE_LOC, 360.0d, 360.0d, false, true); Image image4 = new Image(IMAGE_LOC); ``` -------------------------------- ### Create JavaFX VBox and HBox Application Layout Source: https://fxdocs.github.io/docs/html5/html5 Provides the complete source code for a JavaFX `Application` subclass, `VBoxAndHBoxApp`, demonstrating a complex UI layout using nested `VBox` and `HBox` containers. It includes setting up buttons, hyperlinks, a `TableView` with custom columns, and applying margins and growth priorities to achieve a responsive design. ```Java public class VBoxAndHBoxApp extends Application { @Override public void start(Stage primaryStage) throws Exception { VBox vbox = new VBox(); HBox topControls = new HBox(); VBox.setMargin( topControls, new Insets(10.0d) ); topControls.setAlignment( Pos.BOTTOM_LEFT ); Button btnRefresh = new Button("Refresh"); HBox topRightControls = new HBox(); HBox.setHgrow(topRightControls, Priority.ALWAYS ); topRightControls.setAlignment( Pos.BOTTOM_RIGHT ); Hyperlink signOutLink = new Hyperlink("Sign Out"); topRightControls.getChildren().add( signOutLink ); topControls.getChildren().addAll( btnRefresh, topRightControls ); TableView tblCustomers = new TableView<>(); tblCustomers.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); VBox.setMargin( tblCustomers, new Insets(0.0d, 10.0d, 10.0d, 10.0d) ); VBox.setVgrow( tblCustomers, Priority.ALWAYS ); TableColumn lastNameCol = new TableColumn<>("Last Name"); lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName")); TableColumn firstNameCol = new TableColumn<>("First Name"); firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName")); tblCustomers.getColumns().addAll( lastNameCol, firstNameCol ); Separator sep = new Separator(); HBox bottomControls = new HBox(); bottomControls.setAlignment(Pos.BOTTOM_RIGHT ); VBox.setMargin( bottomControls, new Insets(10.0d) ); Button btnClose = new Button("Close"); bottomControls.getChildren().add( btnClose ); vbox.getChildren().addAll( topControls, tblCustomers, sep, bottomControls ); Scene scene = new Scene(vbox ); primaryStage.setScene( scene ); primaryStage.setWidth( 800 ); primaryStage.setHeight( 600 ); primaryStage.setTitle("VBox and HBox App"); primaryStage.setOnShown( (evt) -> loadTable(tblCustomers) ); primaryStage.show(); } public static void main(String[] args) { launch(args); } private void loadTable(TableView tblCustomers) { tblCustomers.getItems().add(new Customer("George", "Washington")); tblCustomers.getItems().add(new Customer("Abe", "Lincoln")); tblCustomers.getItems().add(new Customer("Thomas", "Jefferson")); } } ``` -------------------------------- ### JavaFX ListView Filtering: Player Data Model Class Source: https://fxdocs.github.io/docs/html5/html5 Defines a `Player` static class, serving as the data model for a JavaFX ListView filtering example. It includes fields for team and player name, along with a `toString()` method for display. ```java static class Player { private final String team; private final String playerName; public Player(String team, String playerName) { this.team = team; this.playerName = playerName; } public String getTeam() { return team; } public String getPlayerName() { return playerName; } @Override public String toString() { return playerName + " (" + team + ")"; } } ```