java - 如何暂停/ sleep Java 程序直到单击按钮

标签 java javafx

我创建了一个 Java 应用程序,它是一个屏幕录像机。首先,我添加了开始和停止录制的功能,但现在也要求添加暂停选项。我希望整个工作在单击“暂停”时停止,并在再次单击时恢复。我无法使用 sleep ,因为它需要时间。

我尝试过等待通知逻辑。有人可以指导我,如何停止代码工作直到再次单击吗?

boolean paused;
    //boolean paused=false;
    @FXML
    private void pauseRec(ActionEvent event) throws AWTException, InterruptedException
    {
        if (paused==false)
        {
            paused= true;
            pauseRec.setText("Resume");
            recordStateLabel.setText("Recording Paused");
            synchronized(threadObject)
            {
                // Pause
                try 
                {
                    threadObject.wait();
                } 
                catch (InterruptedException e) 
                {
                }
            }
            //rob.delay(10000);
        }
        else if(paused ==true)
        {
            paused=false;
            pauseRec.setText("Pause");
            recordStateLabel.setText("Recording..");
            synchronized(threadObject)
            {
                threadObject.notify();
            }
        }
    }

最佳答案

Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), e -> System.out.println("Printed after 1 second from FX thread")));
timeline.play();

So this will pause the current working for 1 sec duration and will resume afterwards. For your case you can make this function to run for finite time and then resume as the resume button is clicked.

Follow this link for more details

关于java - 如何暂停/ sleep Java 程序直到单击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57220874/

相关文章:

java - 包含包装标签的控制皮肤的首选高度

绑定(bind)到 GraphicPropety 的 JavaFX ImageView 未显示在多个 View 上

Javafx:以编程方式关闭警报框(或任何对话框)

java - method.getClass().newInstance() 和 SomeClass.class.newInstance() 之间的区别?

java - 当资源由路径绑定(bind)时使用 Java getResource

java - 如何在java中打印到现有的.csv文件?

css - JavaFX:将 treetableview 展开箭头与行内容对齐

java - 将所有环境(dev uat prod)的 jar 和配置打包在一个 zip 中是否是一种好习惯?

java - OutOfMemoryError 之前的垃圾收集

Java Fx 如何引用类中添加的元素