views:

349

answers:

4

I am creating a SQL editor. I am using JTextPane for the editor. I want to implement AutoCompletion for table name etc. like Eclipse.

+1  A: 

For things like this you probably should consider layered panes so your auto-complete suggestions appear in the correct place and z-order.

Furthermore you will have to look for changes in the JTextPane to know when the user is typing and you will need a parser that understands what is typed so you can offer the feature only at appropriate points.

It's not quite clear what exactly your problem is and what you got so far.

Joey
+1  A: 

I think the appropriate class for displaying info on top of another component is JPopupMenu, which already handles layering correctly to display itself. JPopupMenu has a show() method that takes its 'parent' component as an argument, and it will show itself in that component's coordinate space. Since you want to display a selection of terms for the user to choose from, a menu seems appropriate.

To check for text changes, you'd add a DocumentListener to the document that's wrapped by the JTextPane; you can access it using getDocument().

To find out where the cursor (actually, the caret) is, you can use getCaretPosition(). That returns the caret's position within the text stream as an int. You can use modelToView() to translate that position to actual (x,y) coordinates. That in turn will tell you where to show your menu.

You can use addKeyListener() to catch keyboard events on your JTextPane, like hitting Ctrl-Space.

The combination of all that should allow you to do what you're looking to do.

Carl Smotricz
+1  A: 

I achieved this by adding a key listener to the JTextPane and checking for CTRL + Space keystrokes. When the appropriate key combo was detected the listener went off and looked up the list of possible matches based on the characters directly to the left of the cursor at the time of the key press and found the best matches and displayed them to the user in a JPopup. If there was an exact match then it simply replaced the partial text with the match. If no matches were found an option was given to the user to add the text that they had already typed, edit it and record it into the list of acceptable data.

Antz
Can I just ask - how was it that you did not get "IllegalStateException - attempt to mutate during notification" when you replaced the partial text in the JTextPane with the match?
Arvanem
A: 

You can also use http://fifesoft.com/autocomplete/. You can install it on any JTextComponent.

MarkL