如何使JTextField的一部分不可编辑 [英] How to make part of a JTextField uneditable
本文介绍了如何使JTextField的一部分不可编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想开发一个类似于IDLE的类似于控制台的界面.这涉及确定如何防止JTextField
中的文本的某些部分被编辑.例如:
I wanted to develop a console-like interface, similar to IDLE. That involved determining how to prevent a certain part of the text in a JTextField
from being edited. For example:
>>> help
其中">>>"不可编辑.插入符号一定不能移到某个位置的后面,并且该位置后面的文本不能以任何方式进行编辑.
Where the ">>> " is uneditable. The caret must never move behind a certain position, and the text behind that position cannot be edited in any way.
推荐答案
我看过NavigationFilter,但它似乎并不能阻止键盘驱动的插入符号的操作.
I looked at NavigationFilter, but it doesn't seem to prevent keyboard driven manipulation of the caret.
这显示了如何使用NavigationFilter
做到这一点:
This shows how to do it with a 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();
}
});
}
}
这篇关于如何使JTextField的一部分不可编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文