How can I create an AutoComplete popup in a JTextP

2020-07-22 18:30发布

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

5条回答
趁早两清
2楼-- · 2020-07-22 18:48

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.

查看更多
叛逆
3楼-- · 2020-07-22 18:52

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

查看更多
太酷不给撩
4楼-- · 2020-07-22 18:53

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.

查看更多
虎瘦雄心在
5楼-- · 2020-07-22 18:54

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.

查看更多
Bombasti
6楼-- · 2020-07-22 19:08

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

查看更多
登录 后发表回答