简体   繁体   中英

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" ? to make it "eHllo" ?

I assume you're talking about a JTextField ?

You can programatically set the selection of a JTextField by using the select(int selectionStart, int selectionEnd) method that is inherited from JTextComponent.

As for switching the first two chars, just use the getText() and setText(String newText) methods (with a bit of String manipulation in-between).

Text properties of Swing controls usually don't directly allow to interact with the underlying object used to store the property.

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" . 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) .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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