如何创建在Java中的JTextPane的自动完成弹出? [英] How can I create an AutoComplete popup in a JTextPane in Java?
问题描述
我创建一个SQL编辑器。我使用的JTextPane的编辑器。我想实现对表的名称等。像Eclipse AutoCompletion开始。
I am creating a SQL editor. I am using JTextPane for the editor. I want to implement AutoCompletion for table name etc. like Eclipse.
推荐答案
我觉得对于另一个部件的顶部显示的信息相应的类是的JPopupMenu
,其中已经处理了分层正确显示其自身。 JPopupMenu中有一个显示()
这需要它的父组件作为一个参数的方法,它会显示自己在该组件的坐标空间。既然你要显示一个选择项供用户选择,菜单似乎是恰当的。
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.
要检查文字的变化,你会添加一个的DocumentListener
至由包文件的的JTextPane
;您可以通过访问 getDocument()
。
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()
.
要找出光标(实际上,插入符号),你可以使用 getCaretPosition()
。返回文本流作为 INT
中插入符号的位置。您可以使用 modelToView的()
到该位置转化为实际的(X,Y)坐标。这反过来会告诉你在哪里显示你的菜单。
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.
您可以使用 addKeyListener()
捉对你的的JTextPane
,如按<大骨节病>控制<键盘事件/骨节病> - <大骨节病>空间骨节病>
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.
这篇关于如何创建在Java中的JTextPane的自动完成弹出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!