【问题标题】:How to wait for a JFrame thread to finish from inside a JavaFX application?如何等待 JFrame 线程从 JavaFX 应用程序内部完成?
【发布时间】:2018-06-10 21:49:35
【问题描述】:

我正在尝试从 JavaFX 应用程序中创建一个 JFrame 窗口。我正在使用 Oracle Java 8,我能够在 Linux、Windows 中做我需要的事情,但在 Mac OS 中却不行。这似乎是一个 JVM 实现问题。以下是我的要求:

  • 我需要调用创建游戏窗口的库方法(JFrame 的扩展类)。我需要能够在游戏中使用键盘。
  • 我可以访问库的源代码,但我无意更改库的源代码
  • 我需要在游戏结束后处理游戏信息,所以我的主线程需要等到游戏结束

我在下面创建了示例应用程序。应用程序在 Linux 和 Windows 下运行良好,但在 Mac OS 中,当我尝试等待 JFrame 线程完成应用程序冻结并且未显示 JFrame 时。 SwingUtilities.invokeLater 不会冻结,但不会等待 JFrame 线程完成。由于我需要等待 JFrame 线程,invokeLater 不适合我。

JFrameCreator.java

public class JFrameCreator implements Runnable {
    @Override
    public void run() {
        System.out.println("Creating JFrame");
        JFrame frame=new JFrame();
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.setSize(300,300);
        frame.setVisible(true);
        for (int i = 0; i < 100; i++) {
            frame.getContentPane().getGraphics().drawOval(150-i/2,150-i/2,i,i);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

sample.fxml

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="100.0" prefWidth="200.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <Button layoutX="51.0" layoutY="10.0" mnemonicParsing="false" onAction="#createJFrame" text="New JFrame" />
      <RadioButton fx:id="cbThread" layoutX="10.0" layoutY="40.0" mnemonicParsing="false" selected="true" text="Thread">
         <toggleGroup>
            <ToggleGroup fx:id="tg" />
         </toggleGroup>
      </RadioButton>
      <RadioButton fx:id="cbInvokeWait" layoutX="10.0" layoutY="60.0" mnemonicParsing="false" text="invokeAndWait" toggleGroup="$tg" />
      <RadioButton fx:id="cbInvokeLater" layoutX="10.0" layoutY="80.0" mnemonicParsing="false" text="invokeLater" toggleGroup="$tg" />
   </children>
</AnchorPane>

Controller.java

public class Controller {
    @FXML RadioButton cbThread;
    @FXML RadioButton cbInvokeWait;
    @FXML RadioButton cbInvokeLater;

    public void createJFrame(javafx.event.ActionEvent actionEvent) {
        Runnable r=new JFrameCreator();
        try {
            if (cbThread.isSelected()) {
                Thread t=new Thread(new JFrameCreator());
                t.start();
                t.join();
            }
            else if(cbInvokeWait.isSelected())
                SwingUtilities.invokeAndWait(r);
            else
                SwingUtilities.invokeLater(r);
        }
         catch (InterruptedException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

Main.java

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Swing in JavaFX");
        primaryStage.setScene(new Scene(root, 200, 100));
        primaryStage.show();
    }


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

我还尝试了使用 Thread.isAlive() 方法的 while 循环,但它的行为也类似于 Thread.join()。我怎样才能达到我的要求?

【问题讨论】:

  • 仅供参考:你 for-loop 在哪里“画”东西是一个非常糟糕的主意。
  • 为什么不使用“生产者/消费者”模式——当“swing”部分完成它的工作时,它会通过回调通知“JavaFX”部分
  • @MadProgrammer for 循环可能是一种不好的做法,但我这样做是为了在工作人员中造成一些延迟。对于生产者/消费者,请参阅我的 reply 到 Slaw 的帖子
  • 除了Thread,使用getGraphics是个坏主意

标签: java multithreading macos swing javafx


【解决方案1】:

您可以使用其中一种同步类,例如CountDownLatch。将其传递给您的 Runnable 并在 run() 方法的末尾调用 latch.countDown()。同时,您的 JavaFX 线程将在 latch.await() 上暂停。但是,这将冻结 JavaFX UI,因此这可能不是您想要的。

另一种选择是使用回调。比如:

public class JFrameCreator implements Runnable {

    private final Runnable onFinished;

    public JFrameCreator(Runnable onFinished) {
        this.onFinished = onFinished;
    }

    @Override
    public void run() {
        // do your work...
        Platform.runLater(onFinished); // to communicate to JavaFX Application
                                       // Thread that JFrameCreator is complete
    }

}

第二个选项不会导致 JavaFX 线程等待,但它确实允许您在适当的时间做出反应。您可以将onFinished 的类型更改为您需要的任何类型;比如Consumer,如果你想通过回调一些对象。

【讨论】:

  • CountDownLatch 的行为与 Thread.join() 相同。我需要阻止 JavaFX 应用程序。如果我不这样做,用户可以创建许多游戏实例,因为 JavaFX 应用程序将可用于 JavaFX 组件事件。
  • @caki 如果游戏实例是通过 UI 元素启动的,例如 Button,只需在启动实例时禁用 Button。然后,使用回调选项,在回调中重新启用Button,以便可以启动另一个实例。为了更安全,在Button 的操作处理程序中检查一个实例是否已经在运行,如果有,不要启动另一个。
  • 我在主项目上尝试了您的解决方法。它有效并解决了我的问题。我也想知道为什么在 Mac OS 上尝试加入其他线程会冻结。
猜你喜欢
  • 1970-01-01
  • 2016-08-17
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
  • 2019-09-14
相关资源
最近更新 更多