首页 > 解决方案 > Javafx 标签不显示在窗口中

问题描述

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

标签 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)->{});              
}
}

标签: javajavafxlabel

解决方案


正如 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();

推荐阅读