Как выполнить метод в потоке работы с GUI?

248
24 ноября 2017, 06:51

Main:

public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
    Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
    primaryStage.setTitle("Hello World");
    primaryStage.setScene(new Scene(root, 300, 275));
    primaryStage.show();
    Platform.runLater(new Runnable() {
        @Override public void run() {
            Controller instance2 = new Controller();
            instance2.aaa.setText("123");
        }
    });
}
public static void main(String[] args) {
    launch(args);
}}

Controller:

public class Controller {
    @FXML
    Label aaa;
}

Ошибка:

    Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
  at sample.Main$1.run(Main.java:22)
  at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
  at java.security.AccessController.doPrivileged(Native Method)
  at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
  at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
  at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
  at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
  at java.lang.Thread.run(Thread.java:748)

Ну и на всякий случай sample.fxml:

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <Label fx:id="aaa" layoutX="164.0" layoutY="93.0" text="Label" />
   </children>
</AnchorPane>

У меня та же самая ошибка. Мне объяснили что она появляется из за того, что работать нужно в одном потоке с GUI. Объясните пожалуйста как это сделать.

Answer 1
FXMLLoader loader = new FXMLLoader( getClass().getResource( "sample.fxml" ) );
Controller instance2 = new Controller();
loader.setController( instance2 );
Parent root = loader.load();
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
Platform.runLater(new Runnable() {
    @Override public void run() {
//        Controller instance2 = new Controller();
        instance2.aaa.setText("123");
    }
});
READ ALSO
Можно ли вызвать НЕ synchronized метод &ldquo;заблокированного&rdquo; объекта?

Можно ли вызвать НЕ synchronized метод “заблокированного” объекта?

Есть 2 потока, один из них начал выполнение synchronized метода, внутри которого применяется Threadsleep(5000)

183
В Android Studio ошибка Failed to instantiate one or more classes

В Android Studio ошибка Failed to instantiate one or more classes

Давно не открывал студиюНаверно с лета

320
Как реализовать Spring security

Как реализовать Spring security

У меня есть таблица, в ней username, passwordПодскажите, как мне реализовать Spring security для входа

178