如何使JTextComponent的插入符号跳过所选文本?

时间:2013-03-21 17:54:40

标签: java swing selection caret jtextcomponent

许多环境中本机文本字段的正常行为如下:

带文字“abcdefg”的文字字段。我用鼠标从左到右选择“efg”。插入符号现在落后于“g”。当我通过按左光标键一次将插入符号向左移动时,删除选择并且插入符号在“e”之前。当我在JTextField或JTextArea(在Mac OS上测试)中执行相同操作时,完全相同的操作会导致插入符号在“g”之前。

我知道如何通过使用KeyListener并将其注册到每个组件来以编程方式更改它,但我正在寻找一种方法来更改整个应用程序。那可能吗?有没有国旗,我找不到或者我不得不破解我的外表和感觉?

由于

2 个答案:

答案 0 :(得分:2)

  

我正在寻找一种方法来改变我的整个应用程序

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

public class CaretAction extends TextAction
{
    private boolean caretForward;

    public CaretAction(boolean caretForward)
    {
        super(caretForward ? "Caret Forward" : "Caret Backward");
        this.caretForward = caretForward;
    }

    public void actionPerformed(ActionEvent e)
    {
        JTextComponent textComponent = getFocusedComponent();

        int start = textComponent.getSelectionStart();
        int end = textComponent.getSelectionEnd();
        int offset = textComponent.getCaretPosition();

        if (start != end)
        {
            if (caretForward)
                offset = (offset == end) ? offset + 1 : end;
            else
                offset = (offset == start) ? offset -1 : start;
        }
        else
        {
            offset += (caretForward) ? 1 : -1;
        }

        offset = Math.max(offset, 0);
        offset = Math.min(offset, textComponent.getDocument().getLength());
        textComponent.setCaretPosition( offset );
    }

    private static void createAndShowUI()
    {
        JTextField textField1 = new JTextField(10);
        JTextField textField2 = new JTextField(10);

        JPanel panel = new JPanel();
        panel.add( textField1 );
        panel.add( textField2 );

        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( panel );
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );

        ActionMap map = (ActionMap)UIManager.get("TextField.actionMap");
        map.put(DefaultEditorKit.backwardAction, new CaretAction(false));
        map.put(DefaultEditorKit.forwardAction, new CaretAction(true));
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

您还需要更改JTextArea的ActionMap,JFormattedTextField ......

答案 1 :(得分:1)

您可以做的是addCaretListener

     anyField.addCaretListener(new CaretListener() {
        public void caretUpdate(CaretEvent evt) {
            anyFieldCaretUpdate(evt);
        }
       });

再次将Caret放在最后:

  private void anyFieldCaretUpdate(CaretEvent evt) {

     anyField.setCaretPosition(anyField.getText().length());
        }