簡體   English   中英

當在TextField中鍵入的文本與圖像名稱匹配時,如何在ImageView中顯示圖像?

[英]How do I show an image in ImageView when a typed text into TextField matches with the image name?

我在項目文件夾中放入了一些圖像。 每個圖像都有一個名稱。 例如:a,aa,aba等。當它與在TextField中鍵入的圖像名稱匹配時,我想在ImageView中顯示相關圖像。

例如,如果我在TextField中鍵入“ a”,它將打開名為“ a”的圖像。 如果輸入“ ab”,它將不會打開任何圖像,因為名為“ ab”的圖像文件夾中沒有圖像。 僅當圖像名稱與在TextField中鍵入的文本匹配時,才會顯示圖像。

我寫了一些代碼,如下所示:

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);
    }
}

這是.fxml文件:

<?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>

值得一提的是,在寫入TextField之后,無需再按任何其他“ Enter”鍵即可顯示圖像。

您可以使用綁定:

@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());
}

這假設您的路徑正確(對我來說看起來很奇怪),並且用戶在文本字段中鍵入整個文件名(如有必要,包括文件擴展名)。 您顯然可以根據需要修改File構造函數的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM