考虑一个JFormattedTextField (或者实际上是任何JTextComponent ),其中有一个前缀和一个后缀显示在字段的实际“文本”周围。
例如,双3.5将是字符串"3.50“(通过格式化),其周围将是前缀"$”和后缀"",用于显示文本"$ 3.50“。
显然,这很容易做到。但是,用户仍然可以选择前缀/后缀中的文本,因此他们可以删除部分或全部前缀/后缀。我希望用户受到限制,这样就不能选择前缀/后缀(虽然仍然是文本字段的一部分,因此没有JLabels)。我几乎可以通过CaretListener (或者通过覆盖setCaretPosition/moveCaretPosition)来实现这一点,它可以防止C-a选择整个字段,并防止使用箭头键移动到前缀/后缀中。但是,鼠标拖动和shift-箭头键仍然允许选择移动到这些受限制的区域。
有什么想法吗?
发布于 2011-09-15 02:49:07
为此,您可以使用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);
}
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的工作原理。所以我不确定你是否可以在格式化文本字段中使用它,因为这可能会取代默认行为。
https://stackoverflow.com/questions/7421337
复制相似问题