Suppose there is a Circle Circle circle You need to install an image Image img instead of a fill, tell me how to achieve this.
1 answer
There are at least three ways. Two of these are:
If a dynamic figure is created, use the
setFill()method and pass it an ImagePattern . This is a class with which you can fill a figure with a picture according to a certain pattern.public class Main extends Application { private Rectangle rectangle; // тут прописывается правильный путь до картинки String imageBG = getClass().getResource("myBG.png").toExternalForm(); @Override public void start(Stage stage) throws Exception{ stage.setTitle("Image Pattern"); Group root = new Group(); Scene scene = new Scene(root, 600, 450); // создаем фигуру, в данном случае прямоугольник Rectangle rect = new Rectangle(20, 20, 100, 100); // Заливаем паттерном. Пока тупо картинкой rect.setFill(new ImagePattern(new Image(imageBG))); // Добавляем фигуру root.getChildren().add(rect); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }More details can be found HERE . There are even examples for clarity.
Suppose there is already a figure on the stage, it is drawn and described in the
fxmlfile<Rectangle id="myImg" fx:id="myImage" arcHeight="5.0" arcWidth="5.0" fill="#e1011b" height="97.0" layoutX="43.0" layoutY="121.0" stroke="BLACK" strokeType="INSIDE" width="200.0" />then you can assign it an ID (in this case
myImage). And in the desired controller, we have a field that refers to the object with the given id, specially marked with the@FXMLannotation saying that we take it from FXML.@FXML private Rectangle myImage;And then also apply the pattern. Those. the controller looks something like this:
import javafx.fxml.FXML; import javafx.scene.image.Image; import javafx.scene.paint.ImagePattern; import javafx.scene.shape.Rectangle; public class Controller { @FXML private Rectangle myImage; // тут нужен правильный путь до картинки Image img = new Image(getClass().getResource("myBG.png").toExternalForm()); public void initialize() { myImage.setFill(new ImagePattern(img)); } }The third option is to use
cssstyles and specifically thesetStylemethod (it's better to use a little search
)
- Thanks, it works, and what does the toExternalForm () method do? Rather, in what cases it should be used and in which it does not fit? - arachnoden
- @arachnoden there with different mechanisms Url is converted to a string (after all,
getResourcereturns theURL). But in principle,toString()work - Alexey Shimansky