[英]Javafx Label doesn't display in the window
我正在做一個小項目-一個程序,該程序在設置的分鍾數后關閉計算機,這就是問題開始的地方。
標簽myResponse不在窗口中顯示文本,我也不知道為什么。 我搜索了許多程序,我的使用這個標簽沒有任何不同。
此外,如果我在文本字段中輸入數字並按Enter,則無法使用右上角的“ 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.