首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从另一个线程更新AnchorPane的JavaFX

从另一个线程更新AnchorPane的JavaFX
EN

Stack Overflow用户
提问于 2018-06-04 05:16:19
回答 1查看 110关注 0票数 0

所以我在这个问题上有点卡住了。我有一个非常基本的游戏,你可以用箭头键在网格中移动一艘船。

我添加了另一个线程与一些怪物,应该是自动漫游网格。我可以从print语句中看到线程正在运行,Monster正在移动,但是图像位置没有更新。

我发现了一些类似的问题,并且有很多使用Platfrom.runLater的建议。但我不确定它是否适合我的特定情况,如果是,如何实现它。

下面是Monster类正在做的事情,每秒将怪物向右移动一个空间。正如我前面提到的,每次调用setX()时,我都会记录当前位置,因此我可以看到该位置正在更新。

代码语言:javascript
复制
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.awt.Point;

public class Monster implements Runnable {

    private Point currentPoint;
    private OceanMap map;

    public Monster(int x, int y) {
        this.currentPoint = new Point(x, y);
        this.map = OceanMap.getInstance();
    }

    public Point getLocation() {
        System.out.println(this.currentPoint.toString());
        return this.currentPoint;
    }

    private void setNewLocation(Point newLocation) {
        this.currentPoint = newLocation;
    }

    private void setY(int newY) {
        this.currentPoint.y = newY;
        this.setNewLocation(new Point(this.currentPoint.x, this.currentPoint.y));
    }

    private void setX(int newX) {
        this.currentPoint.x = newX;
        this.setNewLocation(new Point(this.currentPoint.x, this.currentPoint.y));
        System.out.println(this.currentPoint.toString());
    }

//    public void addToPane() {
//        System.out.println("this is called");
//        iv.setX(this.currentPoint.x + 1 * 50);
//        iv.setY(this.currentPoint.y * 50);
//        obsrvList.add(iv);
//    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.setX(this.currentPoint.x + 1);
        }

    }

}

这是JavaFX线程。

代码语言:javascript
复制
/* Monster resources */
private Image monsterImage = new Image(getClass().getResource("monster.png").toExternalForm(), 50, 50, true, true);
private ImageView monsterImageView1 = new ImageView(monsterImage);
private Monster monster1;
private Thread monsterThread;

@Override
public void start(Stage oceanStage) throws Exception {

    root = new AnchorPane();
    scene = new Scene(root, scale * xDimensions, scale * yDimensions);

    oceanStage.setScene(scene);
    oceanStage.setTitle("Ocean Explorer");

    /* Draw Grid */
    for (int x = 0; x < xDimensions; x++) {
        for (int y = 0; y < yDimensions; y++) {
            Rectangle rect = new Rectangle(x * scale, y * scale, scale, scale);
            rect.setStroke(Color.BLACK);
            rect.setFill(Color.PALETURQUOISE);
            root.getChildren().add(rect);
        }
    }

    oceanStage.show();

    monsterThread = new Thread(monster1);
    monsterThread.start();
    Platform.runLater(() -> {
        monsterImageView1.setX(monster1.getLocation().x * scale);
        monsterImageView1.setY(monster1.getLocation().y * scale);
        root.getChildren().add(monsterImageView1);
    });

    startSailing();
}

如果需要,我可以提供更多代码,这是我当时认为相关的所有内容。

同样,我的问题是,如何从另一个线程更新JavaFX线程的UI?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-04 06:43:11

当您在Monster中更新currentPoint时,此值永远不会传播到monsterImageView1。您应该将currentPoint转换为属性,然后绑定到它:

代码语言:javascript
复制
class Point {
    final int x;
    final int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

class Monster implements Runnable {
    private ReadOnlyObjectWrapper<Point> location = new ReadOnlyObjectWrapper<>();

    public Monster(int x, int y) {
        setLocation(new Point(x, y));
    }

    public Point getLocation() {
        return this.location.get();
    }

    private void setLocation(Point location) {
        this.location.set(location);
    }

    public ReadOnlyProperty<Point> locationProperty() {
        return this.location.getReadOnlyProperty();
    }

    private void setY(int newY) {
        this.setLocation(new Point(this.getLocation().x, newY));
    }

    private void setX(int newX) {
        this.setLocation(new Point(newX, this.getLocation().y));
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // run the update on the FX Application Thread for thread safety as well as to prevent errors in certain cases
            Platform.runLater(() -> this.setX(this.getLocation().x + 1));
        }
    }
}

monsterThread = new Thread(monster1);
monsterThread.start();
monsterImageView1.xProperty().bind(Bindings.createIntegerBinding(() -> monster1.getLocation().x * scale, monster1.locationProperty()));
monsterImageView1.yProperty().bind(Bindings.createIntegerBinding(() -> monster1.getLocation().y * scale, monster1.locationProperty()));
root.getChildren().add(monsterImageView1);

然而,正如@James_D提到的,Timeline将是以正确的方式解决这个问题的更好的方法:

代码语言:javascript
复制
class Monster {
    private ReadOnlyObjectWrapper<Point> location = new ReadOnlyObjectWrapper<>();
    private Timeline timeline;

    public Monster(int x, int y) {
        setLocation(new Point(x, y));

        timeline = new Timeline(new KeyFrame(Duration.seconds(1), event -> {
            setX(getLocation().x + 1);
        }));
        timeline.setCycleCount(Timeline.INDEFINITE);
    }

    public void start() {
        timeline.play();
    }

    // NOTE: remember to call stop() or this will result in a memory leak
    public void stop() {
        timeline.stop();
    }

    public Point getLocation() {
        return this.location.get();
    }

    private void setLocation(Point location) {
        this.location.set(location);
    }

    public ReadOnlyProperty<Point> locationProperty() {
        return this.location.getReadOnlyProperty();
    }

    private void setY(int newY) {
        this.setLocation(new Point(this.getLocation().x, newY));
    }

    private void setX(int newX) {
        this.setLocation(new Point(newX, this.getLocation().y));
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50671047

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档