java jtextfield不可编辑,如何使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.

解决方案

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

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

}

});

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值