zl程序教程

您现在的位置是:首页 >  系统

当前栏目

JavaFX快速入门完整代码:点击按钮显示当前系统时间示例

系统入门代码 快速 时间 显示 示例 当前
2023-09-14 09:02:01 时间

最终效果

在这里插入图片描述

sample.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="309.0" prefWidth="349.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <Button fx:id="myButton" layoutX="60.0" layoutY="73.0" mnemonicParsing="false" onAction="#showDateTime" prefHeight="23.0" prefWidth="219.0" text="Show Date Time" />
      <TextField fx:id="myTextField" layoutX="60.0" layoutY="117.0" prefHeight="23.0" prefWidth="219.0" />
   </children>
</AnchorPane>

sample.Controller

package sample;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;

public class Controller implements Initializable {

    @FXML
    private Button myButton;

    @FXML
    private TextField myTextField;
    //更多请阅读:https://www.yiibai.com/javafx/javafx-tutorial-for-beginners.html

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

    // When user click on myButton
    // this method will be called.
    public void showDateTime(ActionEvent event) {
        System.out.println("Button Clicked!");
        Date now= new Date();
        DateFormat df = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss");
        String dateTimeString = df.format(now);
        // Show in VIEW
        myTextField.setText(dateTimeString);
    }


}

sample.Main

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        //primaryStage.setScene(new Scene(root, 800, 600));
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }


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

参考链接

https://www.yiibai.com/javafx/javafx-tutorial-for-beginners.html