-
Highlight Text in JTextField
I'm trying to highlight the text in a JTextField so that the user can either delete the text by typing over it, or edit it by clicking on the text itself.
I'm struggling to find what I need for this - one article I read (here) suggested FocusEvent, but I can't seem to get on with it - I keep getting "addFocusListener cannot be resolved". I've imported awt.event.*, and even tried going all the way with awt.event.FocusEvent, but to no avail.
Each class has several JPanels containing JTextFields. The panels are accessed via 'get' methods, so I don't know if I need to have the FocusListener on the object or the individual panels - I'm guessing it's the object, because the compiler screamed a bit when I tried adding it to the panel.
Can anyone help me out? Many thanks.
-
Hello,
What you are asking for is a bit vague... As far as I undertand your needs you might try:
Code:
mytextField.selectAll(); // select text
mytextField.requestFocusInWindow(); // ask for the focus (maybe unnecessary but...)
Hope that helps,
-
Hmm, thanks for the reply, but that didn't work. To clarify a bit, I have a panel that allows the user to edit the properties of various objects. When the user selects a particular object, that objects properties are shown as strings in the textfields. What I want to do it to have each string highlighted so that a single click will delete the existing text, and gove the user a blank textfield to enter text in.
Thanks again.
-
You could use a HighLighter.
When the hilite is set for a text component you can query that component
for its hiliter. When a hiliter is there you know that it is "selected" and the
first keystroke to that component shall delete the contents, then place the
typed character there and then remove the hiliter.
You make your own hiliter like this:
Code:
import javax.swing.text.*;
import java.awt.*;
class HLPainter extends DefaultHighlighter.DefaultHighlightPainter {
public HLPainter(Color color) {
super(color);
}
}
then you use it like:
Code:
Object hiliteRef=null;
Highlighter hL=aJTextComponent.getHighlighter();
Highlighter.HighlightPainter hp=new HLPainter(Color.yellow); // fancy
try {
hiliteRef=hL.addHighlight(0, aJTextComponent.getText().trim().length(), hp);
} catch (BadLocationException ex) {
System.err.println("HUH??");
}
.
.
// and remove it like:
hL.removeHighlight(hiliteRef);
.
.
-
Brilliant, thank you for the help - I'll give that a go tomorrow
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks