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

求助:如何实现JTextField输入数字时自动每三位添加分隔符?

解决JTextField自动添加千分位分隔符的问题

嘿,我来帮你搞定这个数字自动分隔的需求!你的代码里有几个小问题导致没达到预期效果,咱们一步步来修正:

你之前代码的问题

  1. 错误的JFormattedTextField初始化方式:你把一个JFormattedTextField实例传给另一个的构造器,这不是正确用法——JFormattedTextField的构造器应该接收Format(比如NumberFormat)或者AbstractFormatter,而非另一个同类型组件。
  2. 多余的KeyListener:JFormattedTextField本身就内置了格式化逻辑,手动加KeyListener反而会干扰它的自动处理流程,完全没必要。

正确实现方案

要实现输入数字时自动显示3.000.000这样的格式(千分位用点分隔),我们需要配置正确的NumberFormat,然后直接用它初始化JFormattedTextField即可:

import javax.swing.*;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;

public class NumberTextFieldDemo {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            // 1. 创建并配置NumberFormat,指定千分位分隔符为点
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setGroupingUsed(true); // 启用千分位分组
            DecimalFormatSymbols symbols = new DecimalFormatSymbols();
            symbols.setGroupingSeparator('.'); // 设置千分位分隔符为点
            // 如果需要小数点的话,可以设置小数点分隔符,比如逗号:
            // symbols.setDecimalSeparator(',');
            ((java.text.DecimalFormat) numberFormat).setDecimalFormatSymbols(symbols);

            // 2. 用配置好的NumberFormat创建JFormattedTextField
            JFormattedTextField numberTextField = new JFormattedTextField(numberFormat);
            numberTextField.setValue(0L); // 设置初始值为0
            numberTextField.setColumns(12); // 设置输入框宽度

            // 3. 可选:监听数值变化,获取用户输入的实际数值
            numberTextField.addPropertyChangeListener("value", evt -> {
                Number inputValue = (Number) evt.getNewValue();
                if (inputValue != null) {
                    System.out.println("实际数值:" + inputValue.longValue());
                }
            });

            // 把输入框加到窗口里展示
            JFrame frame = new JFrame("数字千分位分隔示例");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(numberTextField);
            frame.pack();
            frame.setVisible(true);
        });
    }
}

额外优化:限制仅输入数字

如果想确保用户只能输入数字(避免非数字字符),可以给输入框的Document添加DocumentFilter:

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

// 自定义DocumentFilter,只允许输入数字和必要的分隔符
class NumberDocumentFilter extends DocumentFilter {
    @Override
    public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
        if (string.matches("[0-9]")) { // 只允许数字插入
            super.insertString(fb, offset, string, attr);
        }
    }

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
        if (text.matches("[0-9]")) { // 替换时也只允许数字
            super.replace(fb, offset, length, text, attrs);
        }
    }
}

然后给输入框设置这个Filter:

((AbstractDocument) numberTextField.getDocument()).setDocumentFilter(new NumberDocumentFilter());

这样用户就只能输入数字,输入框会自动帮你格式化成千分位带点的样式啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:55:12