简体   繁体   English

如何在文本字段中选择字符?

[英]How do i select a character in a textfield?

is it possible to select a certain character from a textfield ? 是否可以从文本字段中选择某个字符? Is it possible to switch their position as well? 是否可以切换位置?

eg Hello 例如你好

is it possible to switch the position of the "H" with the "e" ? 是否可以用“ e”切换“ H”的位置? to make it "eHllo" ? 使它成为“ eHllo”?

I assume you're talking about a JTextField ? 我假设您正在谈论JTextField

You can programatically set the selection of a JTextField by using the select(int selectionStart, int selectionEnd) method that is inherited from JTextComponent. 您可以通过使用从JTextComponent继承的select(int selectionStart,int selectionEnd)方法以编程方式设置JTextField的选择

As for switching the first two chars, just use the getText() and setText(String newText) methods (with a bit of String manipulation in-between). 至于切换前两个字符,只需使用getText()setText(String newText)方法(之间有一些String操作)。

Text properties of Swing controls usually don't directly allow to interact with the underlying object used to store the property. Swing控件的文本属性通常不允许直接与用于存储该属性的基础对象进行交互。

This means that you won't change directly the string "Hello" already shown onto the table but simply replace it with a new one as "eHllo" . 这意味着您不会直接更改已经显示在表中的字符串"Hello" ,而只需将其替换为新的字符串"eHllo" Then strings are immutable so that's not a big deal. 然后字符串是不可变的,所以没什么大不了的。

You can access or set the string respectively with getText() and setText(String newString) . 您可以分别使用getText()setText(String newString)访问或设置字符串。

(The assertion over visibility of text properties can be considered true for every aspect of Swing, you usually interact by getters and setters as expected in an OOP language) (关于文本属性可见性的断言对于Swing的每个方面都可以认为是正确的,通常您会像在OOP语言中所期望的那样,通过获取和设置者进行交互)

If you want to add/remove characters in the text field then you should do this by using methods of the Document related to the text field. 如果要在文本字段中添加/删除字符,则应使用与文本字段相关的文档方法来执行此操作。 You will find methods like: 您将找到类似的方法:

Document document = textField.getDocument();
document.remove(...);
document.insertString(...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM