JavaFX - 并发和更新标签 [英] JavaFX - Concurrency and updating label
问题描述
我有这些代码段的问题。我想创建一个应用程序,只要按下切换按钮,它就常常在标签中显示随机化的值。这是我创建的,它的工作,但窗口后几秒钟是滞后可怕。
I've got problem with these piece of code. I want to make an application, which constatnly displays randomized values in labels as long as the Toggle Button is pressed. That's what I created, it works but window after a few seconds is lagging horrible. What am I doing wrong?
这里是类的代码,它生成随机值:
Here is code of class, which generate random values:
public class ValueMaker{
private StringPropterty x, y, z;
private Random generator;
private boolean isStarted = false;
private int randomizedX(){ return generator.nextInt(10); }
private int randomizedY(){ return generator.nextInt(10); }
private int randomizedZ(){ return generator.nextInt(10); }
public StringProperty xProperty(){ return x; }
public StringProperty yProperty(){ return y; }
public StringProperty zProperty() { return z; }
public ValueMaker(){
x = new SimpleStringProperty("0");
y = new SimpleStringProperty("0");
z = new SimpleStringProperty("0");
generator = new Random();
}
private void setValues(){
Platform.runLater(new Runnable() {
@Override
public void run() {
x.set(String.valueOf(randomizedX()));
y.set(String.valueOf(randomizedY()));
z.set(String.valueOf(randomizedZ()));
}
});
}
public startRandomize(){
isStarted = true;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (isStarted){
setValues();
}
}
});
t.start();
}
public stopRandomize(){
isStarted = false;
}
}
这里是一段Controller代码,方法:
And here is piece of Controller code, which calls these methods:
@FXML
private void initialize(){
labelX.textProperty().bind(ValueMaker.xProperty());
labelY.textProperty().bind(ValueMaker.yProperty());
labelZ.textProperty().bind(ValueMaker.zProperty());
startRandomizeButton.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (newValue==true){
ValueMaker.startRandomize();
}
else{
ValueMaker.stopRandomize();
}
}
});
}
推荐答案
线程通过连续调用 Platform.runLater
。实现此目标的最佳方法是使用 <$
You are jamming the JavaFX application thread by calling Platform.runLater
continuously. The best way to achieve this would be to use a AnimationTimer
which will be called in each frame while it is active.
AnimationTimer timer = new AnimationTimer() {
@Override
public void handle(long now) {
x.set(String.valueOf(randomizedX()));
y.set(String.valueOf(randomizedY()));
z.set(String.valueOf(randomizedZ()));
}
};
,然后在您的示例中调用计时器:
and then call the timer in your example :
startRandomizeButton.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
// newValue==true is not required
if (newValue){
timer.start();
}
else{
timer.stop();
}
});
}
这篇关于JavaFX - 并发和更新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!