1

Im trying to update the value my text_counter displays based on a change of the value. How do I achieve this? I've read somewhere on SO about binding it, but I have no clue what to bind it to. Anyone that can help me out?

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()); 
3
  • 1
    What is the type of Counter ? Commented Feb 15, 2016 at 20:46
  • its a Counter object. Holds 1 private variable count Commented Feb 15, 2016 at 20:56
  • 1
    Where does it come from? Is it a class you created? If so - you can have the count be a property (IntegerProperty or LongProperty, for example). Then again, if that's all it does, you may as well use a SimpleIntegerProperty etc. to begin with. Commented Feb 15, 2016 at 21:17

1 Answer 1

2

You need to bind the textProperty() of your Text node to the value of your counter. Here is an example of how you can proceed:

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

The binding test:

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

Output:

Before change: Text: 0 Counter: 0 After change: Text: 10 Counter: 10 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. It took me a while to figure out what you were doing as im used to python and ive only just started learning Java but I not understand how it works. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.