按下按钮后,以下JavaFx程序应该在机器上获取当前IP地址并在屏幕上显示。我已经完成了所有工作,但是我在从扩展Task
的类中更新文本时遇到了问题MainApp.java
public class MainApp extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add("/styles/Styles.css");
stage.setAlwaysOnTop(true);
stage.setTitle("IP Viewer");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
我的FXMLController
public class FXMLController implements Initializable {
@FXML
private void handleButtonAction(ActionEvent event) {
Task<Void> task = new IpTask();;
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
IpTask:它获取当前的IP地址并尝试更新用户界面,但我在java.lang.NullPointerException
textIp.setText
例外
public class IpTask extends Task<Void> {
@FXML
private Text textIp;
@Override
protected Void call() throws Exception {
Common common = new Common();
Ip ip = common.getIp();
System.out.println("You clicked me!");
return null;
}
@Override
protected void failed() {
System.out.println("Failed!");
}
@Override
protected void succeeded() {
System.out.println("Updated");
Platform.runLater(new Runnable() {
@Override
public void run() {
textIp.setText("JUST TO SEE IF THE TEXT GETS SET");
}
});
}
}
以下是我的Scene.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="com.limitedenterprisesinc.ipviewer.FXMLController">
<children>
<Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
<!-- <Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" /> -->
<javafx.scene.text.Text layoutX="126" layoutY="140" fx:id="textIp"/>
</children>
</AnchorPane>
如何从IpTask类更新textIp文本字段?
答案 0 :(得分:2)
将字段注入与id times state diffence
3 10 1 -2
5 6 1 -4
7 7 1 1
一起使用的控制器实例。 FXMLLoader
不用作控制器,因此没有任何东西被注入现场。
将字段注入控制器并将其传递给IpTask
。此外,您不必在IpTask
方法中使用Platform.runLater
,因为它是在JavaFX应用程序线程上调用的。
succeeded
public class FXMLController implements Initializable {
@FXML
private Text textIp;
@FXML
private void handleButtonAction(ActionEvent event) {
Task<Void> task = new IpTask(textIp);
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
...
}