更改时更改显示值

changing displayed value upon change

我正在尝试根据值的变化更新我的 text_counter 显示的值。我如何实现这一目标?我在 SO 上的某个地方读过关于绑定它的内容,但我不知道将它绑定到什么。谁能帮帮我?

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

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

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