how to add imageView to javafx region element?

Corsair picture Corsair · Jun 24, 2012 · Viewed 16.4k times · Source

I would like to know how I can add ImageView Elements to a Region Element in JavaFx 2.1.

Maybe I get the usage od this element wrong, but AFAIK it is a container for child elements as well.

The Background is that I need an area of defined size which should display image elements independent of the viewport on the region, so I can't use the Group element as a container.

Answer

jewelsea picture jewelsea · Jun 25, 2012

Use a Pane or a Pane subclass.

Panes are Regions to which you can add children using the getChildren() api. Pane is very similar to a Group; e.g. has a simple api for adding children and does not explicitly layout the location of the children. It also has the aspects of a Region; e.g. css styleable, resize capable, etc. Region's only have an unmodifiable list of children via their public API, meaning that the only way to add children to them is to subclass them (as Pane does for you already). The Region class itself is really just a building block class for control creators and not something you would instantiate during normal development.

Here is an example of adding ImageView nodes to a Pane.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.*;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class RegionSample extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  public void start(Stage stage) throws Exception {
    Pane pane = new Pane();
    pane.setStyle("-fx-background-color: linear-gradient(to bottom right, derive(goldenrod, 20%), derive(goldenrod, -40%));");
    ImageView iv1 = new ImageView(new Image("http://icons.iconarchive.com/icons/kidaubis-design/cool-heroes/128/Ironman-icon.png"));  // Creative commons with attribution license for icons: No commercial usage without authorization. All rights reserved. Design (c) 2008 - Kidaubis Design http://kidaubis.deviantart.com/  http://www.kidcomic.net/ All Rights of depicted characters belong to their respective owners.
    ImageView iv2 = new ImageView(new Image("http://icons.iconarchive.com/icons/kidaubis-design/cool-heroes/128/Starwars-Stormtrooper-icon.png"));
    iv1.relocate(10, 10);
    iv2.relocate(80, 60);
    pane.getChildren().addAll(iv1, iv2);
    stage.setScene(new Scene(pane));
    stage.show();
  }
}