How to implement an auto-complete for a text edito

2019-04-14 07:13发布

问题:

I'm trying to create a text editor like program for coding in mips assembly using java , the point i got mixed up alittle was the part i was trying to provide a Control-Space feature like that of eclipse's.For example when the user enters add $s1 , then presses ctrl+Space , i would replace this string:"add $s1 , $s2 , $s3" with what he has typed! ( that's an example .. i know add can be of immediate type instructions :D ), I'm using a hashmap to bind key strokes to what will actually happen in my JTextPane , sth like :

InputMap inputMap = textPane.getInputMap();
KeyStroke key = KeyStroke.getKeyStroke('some keys') ;
inputMap.put(key, 'some action') ;

well the problem is , when i want to implement Ctrl+Space for my program , i am using this :

key = KeyStroke.getKeyStroke(Event.CTRL_MASK , KeyEvent.VK_SPACE) ;
inputMap.put(key, DefaultEditorKit.insertContentAction);

but where can I select , what string should be inserted instead of the already typed part of the pattern ? other words , where does the insertContentAction bring it strings from ? how can i define what String should be replaced ? or even is there any other better ways for replacing , when Ctrl+Space has been pressed ? (what im asking for is a way to insert the string pattern into a jTextPane , not the algorithm to implement the pattern matching )
Thanks in advance :)

回答1:

You can get the Document of the text pane to make tightly controlled changes such as these. The Document also has some useful events of its own that you can listen for.