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

JavaFX时钟控件无法显示1-12数字的问题排查与修复请求

JavaFX时钟数字不显示问题修复

问题根源

在paintClock()方法中,你先循环创建并添加了1-12的数字文本到Pane的子节点列表,但之后执行了getChildren().clear(),这会把所有已添加的子节点(包括数字)全部清空,最后只添加了时钟外圆、时针、分针、秒针,导致数字被彻底丢弃,无法显示。

修复方案

调整paintClock()方法的执行顺序:先清空旧的子节点,再依次创建所有元素(包括数字),最后将所有元素添加到Pane中。

修改后的paintClock()方法代码

private void paintClock() {
    // 先清空旧内容
    getChildren().clear();
    
    // Initialize clock parameters
    double clockRadius = Math.min(getWidth(), getHeight()) * 0.8 * 0.5;
    double centerX = getWidth() / 2;
    double centerY = getHeight() / 2;

    // Draw circle
    Circle circle = new Circle(centerX, centerY, clockRadius);
    circle.setFill(Color.WHITE);
    circle.setStroke(Color.BLACK);
    getChildren().add(circle);

    // Draw hour markers
    double numberRadius = clockRadius * 0.85;  
    for (int i = 1; i <= 12; i++) {
        double numberX = centerX + numberRadius * Math.sin(i * 2 * Math.PI / 12);
        double numberY = centerY - numberRadius * Math.cos(i * 2 * Math.PI / 12);
        Text number = new Text(numberX - 5, numberY + 5, "" + i);
        number.setFill(Color.BLACK);
        getChildren().add(number);
    }

    // Draw second hand
    double sLength = clockRadius * 0.8;
    double secondX = centerX + sLength * Math.sin(second * (2 * Math.PI / 60));
    double secondY = centerY - sLength * Math.cos(second * (2 * Math.PI / 60));
    Line sLine = new Line(centerX, centerY, secondX, secondY);
    sLine.setStroke(Color.RED);
    getChildren().add(sLine);

    // Draw minute hand
    double mLength = clockRadius * 0.65;
    double xMinute = centerX + mLength * Math.sin(minute * (2 * Math.PI / 60));
    double minuteY = centerY - mLength * Math.cos(minute * (2 * Math.PI / 60));
    Line mLine = new Line(centerX, centerY, xMinute, minuteY);
    mLine.setStroke(Color.BLUE);
    getChildren().add(mLine);

    // Draw hour hand
    double hLength = clockRadius * 0.5;
    double hourX =
            centerX + hLength * Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12));
    double hourY =
            centerY - hLength * Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12));
    Line hLine = new Line(centerX, centerY, hourX, hourY);
    hLine.setStroke(Color.GREEN);
    getChildren().add(hLine);
}

说明

  1. 将getChildren().clear()移到方法最开始,确保每次绘制前清空旧的时钟元素。
  2. 创建每个元素后立即添加到子节点列表,或者也可以最后统一用addAll()一次性添加所有元素(包括数字),两种方式都能保证数字不会被清空操作丢弃。
  3. 原代码中数字的位置计算逻辑是正确的,无需修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 06:24:35