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

如何修改JavaFX Axis的显示值,适配AreaChart的字节与时间格式需求

实现JavaFX AreaChart坐标轴自定义刻度显示的方案

Y轴(NumberAxis)字节单位转可读格式

NumberAxis提供了tickLabelFormatter属性用于自定义刻度的显示文本,你只需要实现一个StringConverter<Number>,在转换逻辑里将原始字节数值转换为KB/MB/GB格式即可。
示例代码:

// 字节转可读单位的工具方法
private String formatByteCount(long bytes) {
    int unit = 1024;
    if (bytes < unit) return bytes + " B";
    int exp = (int) (Math.log(bytes) / Math.log(unit));
    String pre = "KMGTPE".charAt(exp-1) + "";
    return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}

// 给Y轴设置自定义格式化器
NumberAxis yAxis = new NumberAxis();
yAxis.setTickLabelFormatter(new StringConverter<Number>() {
    @Override
    public String toString(Number number) {
        // 直接调用工具方法转换字节数值
        return formatByteCount(number.longValue());
    }

    @Override
    public Number fromString(String s) {
        // 不需要反向转换的话可以直接返回null,或者按需实现解析逻辑
        return null;
    }
});

X轴(CategoryAxis)时间格式化为时分秒

CategoryAxis同样支持tickLabelFormatter属性,你只需要在转换逻辑里将原始的时间值(不管是时间戳还是全量时间字符串)转换为HH:mm:ss格式即可。
如果你的X轴原始数据是毫秒级时间戳字符串,示例代码如下:

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

// 定义时分秒格式化器
private final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");

CategoryAxis xAxis = new CategoryAxis();
xAxis.setTickLabelFormatter(new StringConverter<String>() {
    @Override
    public String toString(String s) {
        long timestamp = Long.parseLong(s);
        LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
        return TIME_FORMATTER.format(time);
    }

    @Override
    public String fromString(String s) {
        // 不需要反向转换可返回null
        return null;
    }
});

如果原始X轴值已经是带年月日的时间字符串,只需要在toString方法里先把字符串解析为时间对象,再格式化输出时分秒即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:57:02