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

Java数字时钟转秒表代码报错求助:setTimer与未定义方法问题

数字时钟切换秒表功能的代码错误修复

我正在开发一款按下空格键可切换为秒表的数字时钟,但代码出现三个错误:

  • setTimer 方法无法接收布尔类型参数
  • isRunning 方法未定义
  • isStopwatchKeyPressed 方法未定义

报错信息:
The code shows that the "setTimer" method is not applicable for the boolean type and the methods "isRunning" and "isStopwatchKeyPressed" are undefined.


ClockProject 类代码(修复后)

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;


public class ClockProject extends JFrame implements KeyListener {
    Calendar calendar;
    SimpleDateFormat timeFormat;
    SimpleDateFormat dayFormat;
    SimpleDateFormat dateFormat;

    JLabel timeLabel;
    JLabel dayLabel;
    JLabel dateLabel;
    String time;
    String day;
    String date;
    ArrayList<String> arrayList;
    private Timer timer; // 替换死循环的Swing定时器
    private boolean stopwatchKeyPressed = false; // 标记是否触发秒表切换

    // 设置时钟格式与外观
    public ClockProject() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Ryan's Digital Clock");
        setLayout(new FlowLayout());
        setSize(350, 220);
        setResizable(false);
        timeFormat = new SimpleDateFormat("hh:mm:ss a");
        dateFormat = new SimpleDateFormat("EEEE");
        dayFormat = new SimpleDateFormat("dd MMMM, yyyy");

        timeLabel = new JLabel();
        timeLabel.setFont(new Font("SANS_SERIF", Font.PLAIN, 59));
        timeLabel.setBackground(Color.BLACK);
        timeLabel.setForeground(Color.WHITE);
        timeLabel.setOpaque(true);

        dayLabel = new JLabel();
        dayLabel.setFont(new Font("Ink Free", Font.BOLD, 34));
        dateLabel = new JLabel();
        dateLabel.setFont(new Font("Ink Free", Font.BOLD, 30));
        add(timeLabel);
        add(dayLabel);
        add(dateLabel);
        setVisible(true);
        arrayList = new ArrayList<String>();
        readFromFile("data.txt");
        for (String data : arrayList) {
            System.out.println(data);
        }
        setTimer(true); // 启动时钟定时器
        addKeyListener(this);
        setFocusable(true);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_SPACE) {
            setTimer(false); // 停止时钟
            stopwatchKeyPressed = true; // 标记切换状态
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.setVisible(true); // 打开秒表窗口
            removeKeyListener(this);
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    // 重载setTimer方法,支持布尔参数控制启停
    public void setTimer(boolean start) {
        int counter = 0;
        if (start) {
            // 创建Swing定时器,每秒触发一次UI更新
            timer = new Timer(1000, e -> {
                time = timeFormat.format(Calendar.getInstance().getTime());
                timeLabel.setText(time);
                day = dayFormat.format(Calendar.getInstance().getTime());
                dayLabel.setText(day);
                date = dateFormat.format(Calendar.getInstance().getTime());
                dateLabel.setText(date);
                timeLabel.setForeground(counter % 2 == 0 ? Color.RED : Color.WHITE);
                counter++;
            });
            timer.start();
        } else {
            if (timer != null) timer.stop();
        }
    }

    // 读取文件内容(方法重载示例)
    public void readFromFile(String filename) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(filename));
            String line = reader.readLine();
            while (line != null) {
                arrayList.add(line);
                line = reader.readLine();
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void writeToFile(String filename) {
        try {
            FileWriter writer = new FileWriter(filename);
            for (String data : arrayList) {
                writer.write(data + "\n");
            }
            writer.close();
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 添加isStopwatchKeyPressed方法,供外部读取切换状态
    public boolean isStopwatchKeyPressed() {
        return stopwatchKeyPressed;
    }

    public static void main(String[] args) {
        // Help.about(); // 假设Help类已实现
        boolean isStopwatchActive = false;
        // 在Swing事件线程中启动UI,符合线程规范
        SwingUtilities.invokeLater(() -> {
            while (true) {
                if (isStopwatchActive) {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.setVisible(true);
                    // 轮询秒表运行状态
                    while (stopwatch.isRunning()) {
                        try { Thread.sleep(100); } 
                        catch (InterruptedException e) { e.printStackTrace(); }
                    }
                    isStopwatchActive = false;
                } else {
                    ClockProject clock = new ClockProject();
                    clock.writeToFile("data.txt");
                    // 轮询是否触发秒表切换
                    while (!clock.isStopwatchKeyPressed()) {
                        try { Thread.sleep(100); } 
                        catch (InterruptedException e) { e.printStackTrace(); }
                    }
                    isStopwatchActive = true;
                    clock.dispose(); // 关闭时钟窗口
                }
            }
        });
    }
}

Stopwatch 类代码(修复后)

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Timer;

public class Stopwatch extends ClockProject implements KeyListener {
    private long startTime;
    private boolean running;
    private long elapsedTime;
    private Timer stopwatchTimer;

    // 秒表构造方法,初始化UI与状态
    public Stopwatch() {
        setTitle("Stopwatch");
        timeLabel.setFont(new Font("SANS_SERIF", Font.PLAIN, 59));
        dayLabel.setVisible(false); // 隐藏日期、星期标签
        dateLabel.setVisible(false);
        setSize(350, 120); // 调整窗口适配秒表显示
        running = false;
        setTimer(); // 启动秒表逻辑
        addKeyListener(this);
        setFocusable(true);
    }

    @Override
    public void setTimer() {
        if (!running) {
            startTime = System.currentTimeMillis();
            running = true;
            // 创建秒表定时器,每18ms更新一次计时
            stopwatchTimer = new Timer(18, e -> {
                if (running) {
                    elapsedTime = System.currentTimeMillis() - startTime;
                    long hours = elapsedTime / 3600000;
                    long minutes = (elapsedTime / 60000) % 60;
                    long seconds = (elapsedTime / 1000) % 60;
                    timeLabel.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
                }
            });
            stopwatchTimer.start();
        }
    }

    // 添加isRunning方法,返回秒表运行状态
    public boolean isRunning() {
        return running;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_SPACE) {
            running = false;
            if (stopwatchTimer != null) stopwatchTimer.stop();
            removeKeyListener(this);
            dispose(); // 关闭秒表窗口
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
}

错误修复说明

  1. setTimer方法无法接收布尔参数:

    • 原代码用死循环+Thread.sleep实现定时,会阻塞Swing事件线程导致UI卡死,替换为javax.swing.Timer实现非阻塞定时更新。
    • 重载setTimer(boolean start)方法,通过布尔参数控制定时器的启停。
  2. isRunning方法未定义:

    • 在Stopwatch类中添加public boolean isRunning()方法,返回私有成员running的状态,供外部判断秒表是否在运行。
  3. isStopwatchKeyPressed方法未定义:

    • 在ClockProject类中添加私有成员stopwatchKeyPressed标记切换状态,空格键按下时设为true,并提供isStopwatchKeyPressed()方法供外部读取。
  4. 额外优化:

    • 所有UI操作放在Swing事件线程中执行,符合Swing线程规范。
    • 秒表窗口隐藏无关标签并调整大小,优化显示效果。
    • 切换功能触发时关闭旧窗口,避免多窗口堆积。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 06:32:13