Question

i have this fxml file

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.effect.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>

<StackPane opacity="1.0" prefHeight="700.0" prefWidth="1024.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="engine.scene.ctrler">
  <children>
    <ImageView fitHeight="701.7022094726562" fitWidth="1235.874704009025" pickOnBounds="true" preserveRatio="true" visible="true" StackPane.alignment="CENTER">
      <effect>
        <Glow level="0.9371069182389937" />
      </effect>
      <image>
        <Image url="@../../../resources/img/bg.jpg" />
      </image></ImageView></children></stackpane>

and i want to change width and height of my imageView any time my scene size changed .i know i should use this

  stage.widthProperty().addListener(new ChangeListener() { 
        @Override
        public void changed(ObservableValue ov, Object t, Object t1) {              
           myImageView.setFitWidth(stage.getWidth());
        }
    });

but i don't know how i can get ImageView from fxml file

Was it helpful?

Solution

I suppose what you need it's a controller.

First you have to add the following as attribute on the StackPane line of the FXML

fx:controller="the.package.ControllerName"

And a attribute on the ImageView with the Id:

fx:id="imageId"

Where of course the.package is the package of the Controller you are going to use.

To implement the controller create a new class with the name you want and extend StackPane and override the initialize method:

package the.package;  

public class ControllerName extends StackPane{

  @FXML
  ImageView imageId;

  @Override
  public void initialize(URL url, ResourceBundle resourceBundle) {
    //You can add code here. 

    //With JavaFX2
    widthProperty().addListener(new ChangeListener() { 
      @Override
      public void changed(ObservableValue ov, Object t, Object t1) {              
        myImageView.setFitWidth(stage.getWidth());
      }
    });

     //With JavaFX8 Using Lambdas
     widthProperty().addListener((ov, t, t1) ->
       myImageView.setFitWidth(getWidth()));         

  }
}

If this do not work you will need to create a new public method in the controller that resizes the ImageView. You can call this method from the stage listener that you have implemented.

Tell me if this is not what you where looking for.

P.S - I have a little project that uses this concepts here!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top