开发者

How can I create an AutoComplete popup in a JTextPane in Java?

I am creating a SQL开发者_如何学Go editor. I am using JTextPane for the editor. I want to implement AutoCompletion for table name etc. like Eclipse.


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.


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


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.


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.


We use jide. They have a lot of components that help you do this kind of thing really easily

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜