官术网_书友最值得收藏!

Clock demo

To demonstrate the topics covered in this chapter, I have written a small clock application.

It will become more complex with each upcoming chapter; for the first release it just shows a current local time in text form and updates it every second, demonstrating Stage/Scene usage, one of the layout managers, and the Application FX Thread workflow:

See the inline comments for details about the program:

// chapter1/clock/ClockOne.java
public class ClockOne extends Application {
// we are allowed to create UI objects on non-UI thread
private final Text txtTime = new Text();

private volatile boolean enough = false;

// this is timer thread which will update out time view every second
Thread timer = new Thread(() -> {
SimpleDateFormat dt = new SimpleDateFormat("hh:mm:ss");
while(!enough) {
try {
// running "long" operation not on UI thread
Thread.sleep(1000);
} catch (InterruptedException ex) {}
final String time = dt.format(new Date());
Platform.runLater(()-> {
// updating live UI object requires JavaFX App Thread
txtTime.setText(time);
});
}
});

    @Override
public void start(Stage stage) {
// Layout Manager
BorderPane root = new BorderPane();
root.setCenter(txtTime);

// creating a scene and configuring the stage
Scene scene = new Scene(root, 200, 150);
stage.initStyle(StageStyle.UTILITY);
stage.setScene(scene);

timer.start();
stage.show();
}

// stop() method of the Application API
@Override
public void stop() {
// we need to stop our working thread after closing a window
// or our program will not exit
enough = true;
}

public static void main(String[] args) {
launch(args);
}
}
主站蜘蛛池模板: 威远县| 绥江县| 马公市| 射阳县| 建湖县| 星子县| 平南县| 博兴县| 望江县| 周口市| 大足县| 元氏县| 准格尔旗| 庆安县| 苏尼特左旗| 梧州市| 永胜县| 临江市| 嘉峪关市| 翁源县| 叶城县| 遂平县| 西林县| 富宁县| 东丰县| 那坡县| 武强县| 通海县| 奉贤区| 怀化市| 阳山县| 江北区| 平罗县| 阿拉善右旗| 上高县| 贵溪市| 许昌市| 沅陵县| 宜川县| 简阳市| 安乡县|