gpt4 book ai didi

JavaFX 更新任务中的文本

转载 作者:行者123 更新时间:2023-11-30 02:48:39 25 4
gpt4 key购买 nike

我想更改文本,我创建了一个任务并递增 i,但我想在更改 i 时在同一位置设置新文本,但旧文本不会消失。这是我的代码。在 Swing 时我将使用 repaint()

Task task = new Task<Void>() {
@Override
public Void call() throws Exception {
int i = 0;
while (true) {
final int finalI = i;
Platform.runLater(new Runnable() {
@Override
public void run() {

String a = "aaa";
if(finalI>4){
a = "sadsa";
}
if(finalI>10){
a = "sadsadsadsadsad";
}
gc.fillText(a, 150, 250+10);
}
});
i++;
Thread.sleep(1000);
}
}
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();

最佳答案

正如我在评论中提到的,问题在于 Canvas 实际上就像一个绘图板。您在其上绘制了一些文本,然后绘制了另一个文本,但没有删除先前的文本。

就您而言,当您想要存储对文本的引用以便能够更新它时,使用 Pane 更为合理。并输入 Text其上的实例。

我为您创建了一个示例:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;

public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 400, 400);

Pane pane = new Pane();
Text text = new Text("");
pane.getChildren().add(text);
Task<Void> task = new Task<Void>() {
String a = "Initial text";

@Override
public Void call() throws Exception {
int i = 0;

while (true) {

if (i > 4)
a = "I is bigger than 4";

if (i > 10)
a = "I is bigger than 10";

Platform.runLater(() -> {
text.setText(a);
// If you want to you can also move the text here
text.relocate(10, 10);
});

i++;
Thread.sleep(1000);
}
}
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();

root.setCenter(pane);
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
launch(args);
}
}

注意:您还可以通过更新 messageProperty 来消除 Platform.runlater(...) block 。 call() 中的任务,然后将 TexttextProperty 绑定(bind)到此属性。

示例:

Pane pane = new Pane();
Text text = new Text("");
text.relocate(10, 10);

pane.getChildren().add(text);
Task<Void> task = new Task<Void>() {
{
updateMessage("Initial text");
}

@Override
public Void call() throws Exception {
int i = 0;

while (true) {
if (i > 4)
updateMessage("I is bigger than 4");

if (i > 10)
updateMessage("I is bigger than 10");

i++;
Thread.sleep(1000);
}
}
};

text.textProperty().bind(task.messageProperty());

Thread th = new Thread(task);
th.setDaemon(true);
th.start();

关于JavaFX 更新任务中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39363601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com