首页 > 编程语言 >用Javafx开发定时器

用Javafx开发定时器

时间:2024-11-10 21:15:46浏览次数:3  
标签:定时器 javafx void Javafx scene private FXML 开发 import

选中小时 分钟 秒

代码附上:

package com.example.javafx03;

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

import java.io.IOException;
import com.example.javafx03.HelloController;
public class HelloApplication extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("hello-view.fxml"));
        Parent root = loader.load();
        stage.setTitle("计时器");
        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("/css/main.css").toExternalForm());
        stage.setScene(scene);
        stage.setResizable(false);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}
--------------------------------------------------------------------------------------
package com.example.javafx03;

import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.util.Duration;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.Media;
public class HelloController  implements Initializable {

    private int second;
    private int minute;
    private  int  hour;
    private Timeline timeline;
    private enum TimeSelect { HOUR , MINUTE , SECOND }
    private TimeSelect selected = TimeSelect.SECOND;
    private MediaPlayer mediaPlayer;
    @FXML
    private Button addButton;
    @FXML
    private Button endButton;

    @FXML
    private Text hourLabel;

    @FXML
    private Text minuteLabel;
    @FXML
    private Text secondLabel;
    @FXML
    private Button reduceButton;
    @FXML
    private Button startButton;
    @FXML
    private Button stopButton;
    @FXML
    private Rectangle hourRectangle;
    @FXML
    private Rectangle minuteRectangle;
    @FXML
    private Rectangle secondRectangle;
    @FXML
    void start(MouseEvent event) {

          initialize();
        // 如果计时器已经在运行,直接返回,避免重复启动
        if (timeline != null && timeline.getStatus() == Animation.Status.RUNNING) {
            return;
        }
          if (hour == 0 && minute == 0 && second == 0){
              return;
          }
        // 创建一个Timeline对象,用于在指定的时间间隔内执行动画
              timeline = new Timeline(new KeyFrame(Duration.seconds(1), e ->{
              if (!decrementTime()){
                  timeline.stop();
                  Platform.runLater(() -> showAlert("计时结束", "时间到了!"));
                  alertSound();
              }
              updateLabel();
        }
        ));
        //代码设置了Timeline的循环次数为无限。这意味着动画会一直重复,直到它被停止或场景关闭。
        timeline.setCycleCount(Timeline.INDEFINITE);
        // 启动动画
        timeline.play();
    }
    public void initialize() {
        hour = Integer.parseInt(hourLabel.getText());
        minute = Integer.parseInt(minuteLabel.getText());
        second = Integer.parseInt(secondLabel.getText());
    }
    public boolean decrementTime(){
        if (second > 0){
            second --;
        }else if (minute >0){
            minute --;
            second = 59;
        }else if(hour > 0){
            hour --;
            minute = 59;
            second = 59;
        }else {
            //已经结束
            timeline.stop();
            return false;
        }
        //还未结束
        return true;
    }
    // 显示警报方法
    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        //当用户关闭弹窗执行操作
        alert.setOnHidden(event -> stopAlertSound());
        //阻塞当前线程,直到用户关闭警报窗口
        alert.showAndWait();
    }
    public void alertSound(){
        // 创建一个Media对象,指定音频文件的路径
        Media media = new Media(getClass().getResource("/alert/11301.mp3").toExternalForm());
        // 创建一个MediaPlayer对象来控制音频播放
        mediaPlayer  = new MediaPlayer(media);
        // 播放声音
        mediaPlayer.play();
    }
    public void stopAlertSound(){
        // 停止音频播放
        mediaPlayer.stop();
    }
    public  void updateLabel(){
        hourLabel.setText(String.format("%02d", hour));
        minuteLabel.setText(String.format("%02d", minute));
        secondLabel.setText(String.format("%02d", second));
    }
    @FXML
    void add(MouseEvent event) {
       switch (selected){
           case HOUR -> updateTime(1, hourLabel, 24);
           case MINUTE -> updateTime(1, minuteLabel, 60);
           case SECOND -> updateTime(1, secondLabel,60);
       }
    }
    @FXML
    void reduce(MouseEvent event) {
        switch (selected){
            case HOUR -> updateTime(-1, hourLabel, 24);
            case MINUTE -> updateTime(-1, minuteLabel, 60);
            case SECOND -> updateTime(-1, secondLabel,60);
        }
    }
    @FXML
    void stop(MouseEvent event) {
        timeline.stop();
    }
    @FXML
    void end(MouseEvent event) {
        timeline.stop();
        hourLabel.setText("00");
        minuteLabel.setText("00");
        secondLabel.setText("00");
    }
    //更新时间方法
    public void updateTime(Integer increment, Text label,Integer max){
        if (timeline != null && timeline.getStatus() == Animation.Status.RUNNING) {
            return;
        }
       int time = Integer.parseInt(label.getText());
       int value = (time + increment) % max;
       if (value >= 0){
           label.setText(String.format("%02d", value));
       }
    }
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        hourRectangle.setOnMouseClicked(event -> {
            selected = TimeSelect.HOUR;
        });
        minuteRectangle.setOnMouseClicked(event -> {
            selected = TimeSelect.MINUTE;
        });
        secondRectangle.setOnMouseClicked(event -> {
            selected = TimeSelect.SECOND;
        });
    }
}
---------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>

<?import java.net.URL?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.shape.Rectangle?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" stylesheets="@../../../css/main.css" xmlns="http://javafx.com/javafx/23.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.javafx03.HelloController">
   <stylesheets>
      <URL value="@/css/main.css" /> <!-- 引用CSS文件 -->
   </stylesheets>
   <children>
      <Rectangle arcHeight="5.0" arcWidth="5.0" fill="#968d8d00" height="209.0" layoutX="55.0" layoutY="45.0" opacity="0.14" stroke="BLACK" strokeType="INSIDE" style="-fx-arc-height: 30; -fx-arc-width: 30;" width="525.0" />
      <Text fx:id="hourLabel" layoutX="85.0" layoutY="177.0" stroke="#dfdfdf" strokeType="INSIDE" text="00" wrappingWidth="106.60003662109375">
         <font>
            <Font name="System Bold Italic" size="73.0" />
         </font>
      </Text>
      <Button fx:id="startButton" layoutX="103.0" layoutY="301.0" mnemonicParsing="false" onm ouseClicked="#start" opacity="0.9" style="-fx-background-radius: 20;-fx-background-image: url('Images/start.png'); -fx-background-size: 50% 50%; -fx-background-repeat: no-repeat; -fx-background-position: center;" />
      <Button fx:id="stopButton" layoutX="273.0" layoutY="301.0" mnemonicParsing="false" onm ouseClicked="#stop" style="-fx-background-radius: 20;-fx-background-image: url('Images/stop.png'); -fx-background-size: 50% 50%; -fx-background-repeat: no-repeat; -fx-background-position: center;" />
      <Button fx:id="addButton" layoutX="189.0" layoutY="301.0" mnemonicParsing="false" onm ouseClicked="#add" style="-fx-background-radius: 20; -fx-background-image: url('Images/add.png'); -fx-background-size: 50% 50%; -fx-background-repeat: no-repeat; -fx-background-position: center; ">
         <font>
            <Font size="11.0" />
         </font>
      </Button>
      <Button fx:id="reduceButton" layoutX="359.0" layoutY="301.0" mnemonicParsing="false" onm ouseClicked="#reduce" style="-fx-background-radius: 20;-fx-background-image: url('/Images/reduce.png'); -fx-background-size: 50% 50%; -fx-background-repeat: no-repeat; -fx-background-position: center;" />
      <Text fx:id="minuteLabel" layoutX="246.0" layoutY="180.0" stroke="#796c63" strokeType="OUTSIDE" strokeWidth="0.0" text="00" wrappingWidth="106.60003662109375">
         <font>
            <Font name="System Bold" size="73.0" />
         </font>
      </Text>
      <Text fx:id="secondLabel" layoutX="421.0" layoutY="180.0" strokeType="OUTSIDE" strokeWidth="0.0" text="00" wrappingWidth="106.60003662109375">
         <font>
            <Font name="System Bold Italic" size="73.0" />
         </font>
      </Text>
      <Text layoutX="192.0" layoutY="171.0" strokeType="OUTSIDE" strokeWidth="0.0" text=":" wrappingWidth="47.4000244140625">
         <font>
            <Font size="73.0" />
         </font>
      </Text>
      <Text layoutX="351.0" layoutY="171.0" strokeType="OUTSIDE" strokeWidth="0.0" text=":" wrappingWidth="47.4000244140625">
         <font>
            <Font size="73.0" />
         </font>
      </Text>
      <Button fx:id="endButton" layoutX="448.0" layoutY="301.0" mnemonicParsing="false" onm ouseClicked="#end" style="-fx-background-radius: 20;-fx-background-image: url('Images/end.png'); -fx-background-size: 50% 50%; -fx-background-repeat: no-repeat; -fx-background-position: center;" />
      <Rectangle fx:id="secondRectangle" arcHeight="5.0" arcWidth="5.0" fill="#818a91" height="165.0" layoutX="413.0" layoutY="61.0" opacity="0.0" stroke="BLACK" strokeType="INSIDE" style="-fx-arc-height: 30; -fx-arc-width: 30;" styleClass="hoverEffect" width="117.0" />
      <Rectangle fx:id="hourRectangle" arcHeight="5.0" arcWidth="5.0" fill="#818a91" height="165.0" layoutX="68.0" layoutY="61.0" opacity="0.0" stroke="BLACK" strokeType="INSIDE" style="-fx-arc-height: 30; -fx-arc-width: 30;" styleClass="hoverEffect" width="123.0" />
      <Rectangle fx:id="minuteRectangle" arcHeight="5.0" arcWidth="5.0" fill="#818a91" height="165.0" layoutX="229.0" layoutY="61.0" opacity="0.0" stroke="BLACK" strokeType="INSIDE" style="-fx-arc-height: 30; -fx-arc-width: 30;" styleClass="hoverEffect" width="117.0" />
   </children>
</AnchorPane>

软件已经打包成exe,感兴趣下载

标签:定时器,javafx,void,Javafx,scene,private,FXML,开发,import
From: https://blog.csdn.net/weixin_67996964/article/details/143649724

相关文章

  • 第 5 章:格式化输出-Claude应用开发教程
    更多教程,请访问:Claude开发应用教程设置运行以下设置单元以加载您的API密钥并建立get_completion辅助函数。!pipinstallanthropic#Importpython'sbuilt-inregularexpressionlibraryimportreimportanthropic#RetrievetheAPI_KEY&MODEL_NAMEvaria......
  • 分享一个超强的网页自动化工具!写得快,跑得快,开发人员狂喜(带私活)
       「今天分享一个开源项目:可控制浏览器,也可收发数据包,可模拟键盘和鼠标的操作」背景做数据采集的同学应该知道,当我们采集要登录的网站时,不仅要分析数据包、JS源码,构造复杂的请求,还要应付验证码、JS混淆、签名参数等反爬手段,门槛较高,开发效率不高。然后使用浏览器,可以......
  • ROS1基础开发环境配置记录(ubuntu20.04+ros-noetic+cartographer)
    一、ROS-Noetic安装1、选择安装源官方默认安装源:sudosh-c'echo"debhttp://packages.ros.org/ros/ubuntu$(lsb_release-sc)main">/etc/apt/sources.list.d/ros-latest.list'国内清华的安装源sudosh-c'./etc/lsb-release&&echo"debhtt......
  • 内核源码+vscode+bear+clang实现函数任意跳转,无缝跳转,无缝阅读,无缝开发
    一、准备工作1、内核源码版本选择务必有一份能编译通过的《内核源码》,本次选择5.10版本的。#说明:5.10版本的《内核源码》里,在scripts/clang-tools目录下有《gen_compile_commands.py》文件,这个脚本也能生成《compile_commands.json》文件。已确定4.19版本没有,请尽量选择高版......
  • Web前端开发--HTML语言
    文章目录前言1.介绍2.组成3.基本框架4.常见标签4.1双标签4.1.1.标题标签4.2.2段落标签4.1.3文本格式化标签4.1.4超链接标签4.1.5视频标签4.1.6音频标签4.2单标签4.2.1换行标签和水平线标签4.2.2图像标签5.表单控件结语前言生活中处处都有网站,无论你是学习爬虫,还......
  • 前端开发规范的学习
    1.KLOC2.数据防腐层3.分治思想4.分层架构模式思想 5.SOLID原则6.关注分离点1.KLOC 定义KLOC是“千行代码”(KiloLinesOfCode)的缩写。它是一种用于衡量软件项目规模大小的指标。通过统计软件项目中代码的行数(以千行为单位)来对项目规模进行量化评估。例如,如果一......
  • 开发分支管理策略
    GitFlow是一种基于Git版本控制系统的分支管理模型,定义了一套严格的分支命名和操作规范主要包括以下几种分支类型:主干分支(master):始终保持稳定,只包含经过充分测试和可发布的代码开发分支(develop):团队成员在该分支上进行日常的开发工作,所有的新功能和特性都先在这个分支上进行......
  • 【大模型应用开发 动手做AI Agent】Agent的感知力:语言交互能力和多模态能力
    AIAgent,语言交互,多模态感知,大模型应用,自然语言处理,计算机视觉1.背景介绍在人工智能领域,AIAgent(智能代理)作为一种能够感知环境、做出决策并与环境交互的智能体,扮演着越来越重要的角色。一个强大的AIAgent需要具备敏锐的感知能力,才能有效地理解和响应周围世......
  • DAY109代码审计-PHP模型开发篇&动态调试&反序列化&变量覆盖&TP框架&原生POP链
    知识点1、PHP审计-动态调试-变量覆盖2、PHP审计-动态调试-原生反序列化3、PHP审计-动态调试-框架反序列化PHP常见漏洞关键字SQL注入:selectinsertupdate deletemysql_querymysqli等文件上传:$_FILES,type="file",上传,move_uploaded_file()等XSS跨站:printprint_r......
  • 【大模型应用开发 动手做AI Agent】Agent带来新的商业模式和变革
    大模型、AIAgent、应用开发、商业模式、变革、智能化、自动化1.背景介绍近年来,人工智能(AI)技术取得了飞速发展,特别是大模型的涌现,为AI应用带来了前所未有的机遇。大模型,是指参数规模庞大、训练数据海量的人工智能模型,具备强大的泛化能力和学习能力,能够在自然语言处理、......