gpt4 book ai didi

java - 如何使 JTextField 的一部分不可编辑

转载 作者:行者123 更新时间:2023-12-01 22:47:11 26 4
gpt4 key购买 nike

我想开发一个类似控制台的界面,类似于 IDLE。这涉及确定如何防止 JTextField 中文本的特定部分被编辑。例如:

>>> help

其中“>>>”不可编辑。插入符号绝不能移到某个位置后面,并且该位置后面的文本不能以任何方式编辑。

最佳答案

I looked at NavigationFilter, but it doesn't seem to prevent keyboard driven manipulation of the caret.

这展示了如何使用NavigationFilter来做到这一点:

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);
}

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

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

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

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

private static void createAndShowUI()
{
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);
}

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

关于java - 如何使 JTextField 的一部分不可编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25168332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com