You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将GUI输入值传入Duration.ofMinutes()实现倒计时计数器

解决文本框输入整数设置倒计时Duration的问题

嘿,这个问题我熟!你要做的核心就是把文本框里的用户输入转换成整数,再传给Duration.ofMinutes(),还要做好输入校验避免程序崩掉。下面一步步给你说具体实现:

  • 第一步:获取并校验文本框输入
    首先从你的GUI文本框(比如Swing的JTextField)里拿到输入的字符串,先trim掉前后空格,然后转成int类型。这里必须加异常处理,不然用户输个字母或者乱七八糟的内容,程序直接炸。

    示例代码:

    // 假设你的文本框实例叫inputMinuteField
    String inputContent = inputMinuteField.getText().trim();
    int targetMinutes = 0;
    
    try {
        targetMinutes = Integer.parseInt(inputContent);
        // 额外加个判断:倒计时总不能是0或者负数吧?
        if (targetMinutes <= 0) {
            JOptionPane.showMessageDialog(null, "麻烦输入大于0的整数哦!");
            return;
        }
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "请输入有效的数字呀!");
        return;
    }
    
  • 第二步:更新你的类变量duration
    拿到合法的分钟数后,直接替换掉原来的初始值就行:

    // 用用户输入的分钟数生成新的Duration,覆盖原来的初始值
    this.duration = Duration.ofMinutes(targetMinutes);
    
  • 第三步:启动倒计时逻辑
    接下来就是让倒计时跑起来,比如用ScheduledExecutorService来每秒减少duration的时间,同时更新GUI显示。这里要注意:更新GUI必须在事件调度线程(EDT)里做,不然会有线程安全问题。

    简单的示例代码:

    ScheduledExecutorService countdownScheduler = Executors.newSingleThreadScheduledExecutor();
    countdownScheduler.scheduleAtFixedRate(() -> {
        // 每秒减少1秒
        this.duration = this.duration.minusSeconds(1);
        // 把Duration转成易读的时分秒格式
        long hours = duration.toHours();
        long remainingMins = duration.toMinutes() % 60;
        long remainingSecs = duration.getSeconds() % 60;
        String displayText = String.format("%02d:%02d:%02d", hours, remainingMins, remainingSecs);
    
        // 切换到EDT线程更新GUI组件(比如显示倒计时的标签)
        SwingUtilities.invokeLater(() -> {
            countdownDisplayLabel.setText(displayText);
        });
    
        // 倒计时结束就停止任务
        if (duration.isZero()) {
            countdownScheduler.shutdown();
            JOptionPane.showMessageDialog(null, "时间到!");
        }
    }, 0, 1, TimeUnit.SECONDS);
    

如果你的GUI用的是JavaFX而不是Swing,逻辑基本一致,只是组件方法和线程更新方式略有不同:比如JavaFX的TextField用getText(),更新UI要用Platform.runLater()。

内容的提问来源于stack exchange,提问作者csibman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:48:16