【问题标题】:How to enter text at the beginning of JTextField如何在 JTextField 的开头输入文本
【发布时间】:2020-06-01 06:19:26
【问题描述】:

有没有一种方法可以添加功能,使用户能够在 JTextField 中键入但光标停留在输入的开头,从而使文本向后?

例子:

用户类型“5”

显示 5 个

用户输入“9”

显示95

【问题讨论】:

  • 您可以读取用户键入的最新字符,然后将带有开头字符的字符串打印到 JTextField 中

标签: java swing jtextfield


【解决方案1】:

如果您只需要对数字进行此操作,我建议您使用JSpinner 组件而不是JTextField。但是使用 textField 你可以像这样实现它:

    JTextField field = new JTextField();
    AbstractDocument document = (AbstractDocument) field.getDocument();
    document.setDocumentFilter(new DocumentFilter() {
        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
                throws BadLocationException {
            offset = 0;//Insert string at offset 0
            super.insertString(fb, offset, string, attr);
        }
        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
                throws BadLocationException {
            offset = 0; //Insert string at offset 0
            super.replace(fb, offset, length, text, attrs);
        }
    });

【讨论】:

    猜你喜欢
    • 2016-03-23
    • 1970-01-01
    • 2012-03-20
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多