Javafx Label不会显示在窗口中

问题描述 投票:-1回答:1

我正在制作一个小项目 - 一个程序,在设定的分钟数后关闭计算机,这就是问题开始的地方。

标签myResponse不会在窗口中显示文本,我也不知道为什么。我搜索了很多程序,并且我没有使用这个标签。

此外,如果我在文本字段中输入数字并按回车键,则无法使用右上角的“x”关闭程序。

我将非常感谢帮助我解决这些问题。提前致谢。

这是一个代码:

import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.event.*;
import javafx.geometry.*;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CompSwitchOff extends Application  {

Label myText;
Label myResponse;
Button btn= new Button ("press enter.");
TextField tf;
String s= "";
int i;

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

public void start (Stage myStage){

    myStage.setTitle("TIMER");
    FlowPane rootNode= new FlowPane(20,20);
    rootNode.setAlignment(Pos.CENTER);
    Scene myScene= new Scene (rootNode,230, 200);
    myStage.setScene(myScene);
    myText= new Label ("how many minutes to shut down the computer?: ");
    myResponse= new Label(); 
    tf= new TextField ();
    tf.setPrefColumnCount(10);
    tf.setPromptText("Enter time to count.");



    tf.setOnAction( (ae)-> {

        s= tf.getText();
        myResponse.setText("computer will switch off in "+ s+ " minuts.");
        i= Integer.parseInt(s)*60000;

        try{ Thread.sleep(i);}
        catch (InterruptedException ie){}

        Process process;
        try{
            process=Runtime.getRuntime().exec("shutdown -s -t 0");
        }
        catch (IOException ie){

        }  
    }
    );
    btn.setOnAction((ae)->{
        s= tf.getText();
        myResponse.setText("computer will switch off in "+ s+ " minuts.");
        i= Integer.parseInt(s)*60000;

        try{ Thread.sleep(i);}
        catch (InterruptedException ie){}

        Process process;
        try{
            process=Runtime.getRuntime().exec("shutdown -s -t 0");
        }
        catch (IOException ie){

        }  

    }
    );

    rootNode.getChildren().addAll(myText, tf, btn, myResponse);
    myStage.show();
    myStage.setOnHidden((eh)->{});              
}
}
java javafx label
1个回答
2
投票

正如Zephyr已经指出的那样,Thread.sleep()方法阻止了整个方法的进一步执行。如果添加一些日志语句,可以看到程序在Thread.sleep(i)之后停止。虽然您的标签文本在Thread.sleep(i)之前设置,但GUI重绘可能在此之后发生。

因此,为了使其运行,您应该将Thread.sleep(i)添加到新线程中,并且它不能阻止主(GUI)线程。

例如:

new Thread(() -> {
    try {
        Thread.sleep(i);
    } catch (InterruptedException e) {
        System.out.println(e.getMessage());
    }
    Process process;
    try {
        process = Runtime.getRuntime().exec("shutdown -s -t 0");
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}).start();
© www.soinside.com 2019 - 2024. All rights reserved.