I've some images into the project folder. Each image has a name. For example: a, aa, aba etc. I want to show the related image into ImageView when it matches an image name typed into the TextField.
For example if I type 'a' into the TextField it will open the image named 'a'. If I type "ab", it won't open any image as there is no image into the image folder named "ab". An image will be only shown when it's name get matched with the text typed into the TextField.
I've written some code as follows-
Application_Controler.java
public class Application_Controler implements Initializable{
@FXML
private TextField txt;
@FXML
private ImageView img;
@Override
public void initialize(URL url, ResourceBundle rb) {
String text=txt.getText();
File file = new File("src/images/"+text);
Image image = new Image(file.toURI().toString());
img.setImage(image);
}
}
Here is the .fxml file:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.image.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="imran.jfx.application.Application_Controler">
<children>
<AnchorPane layoutX="-17.0" layoutY="-14.0" prefHeight="461.0" prefWidth="454.0">
<children>
<TextField fx:id="txt" layoutX="122.0" layoutY="87.0" prefHeight="55.0" prefWidth="229.0" />
<ImageView fx:id="img" fitHeight="281.0" fitWidth="426.0" layoutX="24.0" layoutY="175.0" pickOnBounds="true" preserveRatio="true" />
</children>
</AnchorPane>
</children>
</AnchorPane>
One thing to mention that it won't need to press any extra "Enter" key to show the image after writing to the TextField.
You can use a binding:
@Override
public void initialize(URL url, ResourceBundle rb) {
img.imageProperty().bind(Bindings.createObjectBinding(() -> {
File file = new File("src/images/"+txt.getText());
if (file.exists()) {
return new Image(file.toURI().toString());
} else {
return null ;
}
}, txt.textProperty());
}
This assumes that your path is correct (it looks odd to me) and that the user is typing the entire filename in the text field (including file extension, if necessary). You can obviously modify the argument to the File
constructor as needed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.