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

这篇博客详细介绍了如何在Java Swing应用程序中创建并使用CaretAction,以实现在JTextComponent(如JTextField和JTextArea)中的光标移动功能。通过自定义ActionMap,实现了向前和向后移动光标的快捷操作,使得用户可以更方便地编辑文本内容。
摘要由CSDN通过智能技术生成

I am looking for a way to change that for my entire application

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,JFormattedTextField更改ActionMap …

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值