改变后改变显示值

时间:2016-02-15 20:44:29

标签: java javafx binding

我试图根据值的变化更新text_counter显示的值。我该如何实现这一目标?我已经在某处读过有关绑定它的内容,但我不知道将它绑定到什么地方。任何可以帮助我的人?​​

public class main extends Application implements EventHandler<ActionEvent>{

Button button;
Button button2;
Counter counter = new Counter(0);
Text text_counter = new Text(Integer.toString(counter.getCount()));

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("Counter Window");

    button = new Button();
    button2 = new Button();
    button.setText("Reset");
    button.setOnAction(this);
    button2.setText("Tick");
    button2.setOnAction(this);
    button.setTranslateY(-120);
    button2.setTranslateY(-120);
    button2.setTranslateX(50);
    text_counter.textProperty().bind(counter.getCount());

1 个答案:

答案 0 :(得分:2)

您需要将textProperty() 节点Text绑定到计数器的值。以下是您可以继续操作的示例:

class Counter {
    // The StringProperty to whom the Text node's textProperty will be bound to
    private StringProperty counter; 

    public Counter() {
        counter = new SimpleStringProperty();
    }

    public Counter(int count) {
        this();
        counter.set(Integer.toString(count));
    }

    public void set(int count) {
        counter.set(Integer.toString(count));
    }
}

绑定测试:

// Create the counter
Counter c = new Counter(0);

// The Text node
Text text_counter = new Text(c.counter.get());

// Bind textProperty() to c.counter, which is a StringProperty
// Any changes to the value of c.counter will be reflected on the
// text of your Text node
text_counter.textProperty().bind(c.counter);

System.out.println("Before change:");
System.out.println(String.format("Text: %s Counter: %s",
        text_counter.textProperty().get(),
c.counter.get()));

c.counter.set("10"); // Make a change

System.out.println("After change:");
System.out.println(String.format("Text: %s Counter: %s",
        text_counter.textProperty().get(),
c.counter.get()));

输出:

Before change:
Text: 0 Counter: 0
After change:
Text: 10 Counter: 10