Java JTextField/JTextComponent中的有限选择?

Java JTextField/JTextComponent中的有限选择?,java,swing,text,selection,restrict,Java,Swing,Text,Selection,Restrict,考虑一个JFormattedTextField(或者任何JTextComponent),其中有一个前缀和一个后缀显示在字段的实际“文本”周围 例如,双精度3.5将是字符串(通过格式化)“3.50”,其周围将是前缀“$”和后缀“”,用于显示文本“$3.50” 显然,这很简单。但是,用户仍然可以选择前缀/后缀中的文本,因此他们可以删除部分或全部前缀/后缀。我希望对用户进行限制,这样就根本无法选择前缀/后缀(而仍然是文本字段的一部分,因此没有jlabel)。我几乎可以通过CaretListener(或

考虑一个JFormattedTextField(或者任何JTextComponent),其中有一个前缀和一个后缀显示在字段的实际“文本”周围

例如,双精度3.5将是字符串(通过格式化)“3.50”,其周围将是前缀“$”和后缀“”,用于显示文本“$3.50”

显然,这很简单。但是,用户仍然可以选择前缀/后缀中的文本,因此他们可以删除部分或全部前缀/后缀。我希望对用户进行限制,这样就根本无法选择前缀/后缀(而仍然是文本字段的一部分,因此没有jlabel)。我几乎可以通过CaretListener(或者通过重写setCaretPosition/moveCaretPosition)来完成这一点,这会阻止C-a选择整个字段,并阻止使用箭头键移动到前缀/后缀中。但是,鼠标拖动和shift箭头键仍允许选择移动到这些限制区域


有什么想法吗?

您可以为此使用导航过滤器

下面是一个让您开始学习的示例:

import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

public class NavigationFilterPrefixWithBackspace extends NavigationFilter
{
    private int prefixLength;
    private Action deletePrevious;

    public NavigationFilterPrefixWithBackspace(int prefixLength, JTextComponent component)
    {
        this.prefixLength = prefixLength;
        deletePrevious = component.getActionMap().get("delete-previous");
        component.getActionMap().put("delete-previous", new BackspaceAction());
        component.setCaretPosition(prefixLength);
    }

    public void setDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias)
    {
        fb.setDot(Math.max(dot, prefixLength), bias);
    }

    public void moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias)
    {
        fb.moveDot(Math.max(dot, prefixLength), bias);
    }

    class BackspaceAction extends AbstractAction
    {
        public void actionPerformed(ActionEvent e)
        {
            JTextComponent component = (JTextComponent)e.getSource();

            if (component.getCaretPosition() > prefixLength)
            {
                deletePrevious.actionPerformed( null );
            }
        }
    }

    public static void main(String args[]) throws Exception {

        JTextField textField = new JTextField("Prefix_", 20);
        textField.setNavigationFilter( new NavigationFilterPrefixWithBackspace(7, textField) );

        JFrame frame = new JFrame("Navigation Filter Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(textField);
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}

我相信这就是JFormattedTextField的工作原理。因此,我不确定您是否可以将其与格式化文本字段一起使用,因为它可能会取代默认行为。

我想感谢您的回答,导航过滤器显然是正确的解决方案。关于格式化文本字段,AbstractFormatter有一个可重写的getNavigationFilter(),它将其中一个应用于该字段。那正是我需要的。