java - 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)->{});
}
}
解决方案
正如 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();
推荐阅读
- gremlin - 通过应用程序负载均衡器连接到 AWS Neptune
- solidworks - 如何在 Solidworks 的装配文件中获取所选组件的所有尺寸?
- javascript - 如何从 background.js 调用打开并动态创建新选项卡的内容脚本
- sql - 在 SQLite 中选择带有分隔符的字符串列,如数组
- listview - 将文本从 Arraylist 添加到 TextArea javafx
- xml - 从 url 了解 Web 服务中使用哪种编程语言
- struct - Fortran - 可分配派生类型的可分配数组
- php - 在 PHP 中转换 2018 年 8 月 t0 2018-08-01
- android - 我们能否构建一个具有 v3 依赖项的 AAR,而不会与 v2 的客户端应用程序依赖项发生冲突?
- javascript - 如何从 Redux 字段一次渲染 2 个字段