2016-04-06 51 views
0

我有一個框架,與文本字段,佈局是naff但那不是目前的目標。更新字符串屬性根據文本字段條目

我想,不管以何種輸入到文本字段更新字符串屬性,然後把它在下面的控制檯還打印出來(蝕)

類似於通過調用.SET代碼本身內更新( )

這裏是我的代碼 -

import javafx.application.Application; 
import javafx.beans.property.SimpleStringProperty; 
import javafx.beans.property.StringProperty; 
import javafx.stage.Stage; 
import javafx.scene.Scene; 
import javafx.scene.control.TextField; 
import javafx.scene.layout.Pane; 
import javafx.scene.text.Font; 

public class TextEntry extends Application 
{ 
    private static StringProperty text = 
      new SimpleStringProperty("text"); 

    public static void main(String [] args) 
    { 
     launch(args); 
    } 
    public void start(Stage primaryStage) 
    { 
     Pane root = new Pane(); 

     TextField enterText = new TextField(); 
     enterText.setFont(Font.font("SanSerif",20)); 

     enterText.setOnMousePressed(e ->{ 
      text.bind(enterText.textProperty()); 
      System.out.println("the new value is: " + text); 
     }); 

     root.getChildren().addAll(enterText); 
     Scene scene = new Scene(root,600,600); 
     primaryStage.setScene(scene); 
     primaryStage.setTitle("Text Entry"); 
     primaryStage.show(); 
    } 
} 

我已經嘗試了幾件事情,包括在上面的代碼行 -

text.set("").bind(enterText.textProperty()); 

text.textProperty().bind(enterText.textProperty()); 

其中第二個語法不正確我知道,但我不能想到了解決辦法,任何想法?

回答

0

您只需將屬性綁定一次,而不是每次按下某個鍵。然後,只需添加一個ChangeListener的財產:

public void start(Stage primaryStage) { 
    Pane root = new Pane(); 

    TextField enterText = new TextField(); 
    enterText.setFont(Font.font("SanSerif",20)); 

    text.bind(enterText.textProperty()); 

    text.addListener((obs, oldTextValue, newTextValue) -> 
     System.out.println("The new value is "+newTextValue)); 

    root.getChildren().addAll(enterText); 
    Scene scene = new Scene(root,600,600); 
    primaryStage.setScene(scene); 
    primaryStage.setTitle("Text Entry"); 
    primaryStage.show(); 
} 

當然,上面的額外屬性的代碼是多餘的:你可以做

enterText.textProperty().addListener((obs, oldTextValue, newTextValue) -> 
    System.out.println("The new value is "+newTextValue)); 

但也許還有其他原因,你需要額外的屬性。

+0

多數民衆贊成,謝謝!那開始讓我有些煩惱了! – Treeno1