2016-02-15 6 views
1

Im пытается обновить значение, которое отображает мой 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

Что такое тип 'Counter'? –

+0

его счетчик объекта. Удерживает 1 счетчик личных переменных –

+1

Откуда он? Это класс, который вы создали? Если это так - вы можете иметь счетчик как свойство (например, IntegerProperty или 'LongProperty'). Опять же, если это все, что угодно, вы можете также использовать «SimpleIntegerProperty» и т. Д. – Itai

ответ

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 
+0

Большое вам спасибо. Мне потребовалось некоторое время, чтобы понять, что вы делаете, поскольку я использовал python, и я только начал изучать Java, но я не понимаю, как это работает. Благодаря! –

+0

Добро пожаловать @DennisLukas –

Смежные вопросы