Java 如何使用 Swing 实现自动完成?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/485530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:15:30  来源:igfitidea点击:

How could I implement autocompletion using Swing?

javaswingautocomplete

提问by Geo

I'm interested in providing an autocompletion box in a JFrame. The triggering mechanism will be based on mnemonics (I think), but I'm not really sure what to use for the "autocompletion box" (I would like results to be filtered as the user presses keys).

我有兴趣在 JFrame 中提供一个自动完成框。触发机制将基于助记符(我认为),但我不确定“自动完成框”使用什么(我希望在用户按键时过滤结果)。

How would you implement this? Some sort of JFrame, or a JPopupMenu?

你将如何实现这一点?某种 JFrame 或 JPopupMenu?

I would like to know how this is implemented, so please don't post links to available [J]Components.

我想知道这是如何实现的,所以请不要发布指向可用 [J] 组件的链接。

采纳答案by ivan_ivanovich_ivanoff

There is an example for auto-completion for text area at
Sun's tutorials "Using Swing Components".


Sun 的教程“使用 Swing 组件”中有一个自动完成文本区域的示例

It is done in the style of word processors (no pop ups, but the
suggested text is typed ahead of the cursor).

它以文字处理器的风格完成(没有弹出窗口,但
建议的文本在光标之前输入)。

Just scroll down to "Another Example: TextAreaDemo"
ant hit the Launch button!

只需向下滚动到“另一个示例:TextAreaDemo”
蚂蚁点击启动按钮!

回答by Peter Lawrey

I would add a actionListener so you can get each key as it is pressed.

我会添加一个 actionListener 以便您可以在按下每个键时获取它。

You can can then do a search in the background (another thread)

然后您可以在后台进行搜索(另一个线程)

回答by Geekygecko

You might want to try the free AutoComplete component over at SwingLabs.

您可能想在 SwingLabs 尝试免费的 AutoComplete 组件。

http://swinglabs.org

http://swinglabs.org

Edit: This site seems to have moved http://java.net/projects/swinglabs

编辑:这个网站似乎已经移动了http://java.net/projects/swinglabs

There is an example how to implement this code at:

有一个示例如何实现此代码:

http://download.java.net/javadesktop/swinglabs/releases/0.8/docs/api/org/jdesktop/swingx/autocomplete/package-summary.html

http://download.java.net/javadesktop/swinglabs/releases/0.8/docs/api/org/jdesktop/swingx/autocomplete/package-summary.html

回答by ivan_ivanovich_ivanoff

Hereis an example with a pop-up as you requested. You can launch this example at the bottom of the page.

是一个根据您的要求弹出窗口的示例。您可以在页面底部启动此示例。

Here is my simplified example. Sadly, you have to click the text field first, before start typing, or you'll get exceptions. If anyone can figure out why, please let me know/update this answer.

这是我的简化示例。遗憾的是,您必须先单击文本字段,然后才能开始键入,否则会出现异常。如果有人能弄清楚原因,请告诉我/更新此答案。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class _Autocompleter {

  private final static JPopupMenu textPopupMenu
      = new JPopupMenu("MENU") {

    {
      add(new JMenuItem("item 1"));
      add(new JMenuItem("item 2"));
      setFocusable(false);
    }

  };

  private final static KeyListener textInputListener
      = new KeyAdapter() {

    @Override
    public void keyTyped(KeyEvent e) {
      Point p = textInput.getCaret().getMagicCaretPosition();
      if (textPopupMenu.isVisible()) {
        SwingUtilities.convertPointToScreen(p, textInput);
        textPopupMenu.setLocation(p.x, p.y + 20);
      } else {
        textPopupMenu.show(textInput, p.x, p.y + 20);
      }
    }

  };

  private final static JTextArea textInput
      = new JTextArea("type something") {

    {
      addKeyListener(textInputListener);
      setCaretPosition(getText().length());
    }

  };

  private final static JFrame f = new JFrame("TEST") {

    {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      add(textInput);

      setSize(400, 60);
      setLocationRelativeTo(null);
      setVisible(true);
    }

  };

  public static void main(String[] args)
      throws Exception {
        // YES, IT'S EMPTY !!!
        // It'll start anyway because of static initializers
  }

}

回答by ivan_ivanovich_ivanoff

Use this

用这个

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Autocompleter2
{
    //~ Methods ------------------------------------------------------------------------------------

    public static void main(String[] args)
      throws Exception
    {
        // YES, IT'S EMPTY !!!
        // It'll start anyway because of static initializers
        SwingUtilities.invokeLater(new Runnable()
            {
                @Override
                public void run()
                {
                    final JPopupMenu textPopupMenu = new JPopupMenu("MENU")
                    {

                        {
                            add(new JMenuItem("item 1"));
                            add(new JMenuItem("item 2"));
                            setFocusable(false);
                        }
                    };

                    final JTextArea textInput = new JTextArea("type something la")
                    {

                        {
                            setCaretPosition(getText().length());
                        }
                    };

                    KeyListener textInputListener = new KeyAdapter()
                    {
                        @Override
                        public void keyTyped(KeyEvent e)
                        {
                            Point p = textInput.getCaret().getMagicCaretPosition();

                            if (textPopupMenu.isVisible())
                            {
                                SwingUtilities.convertPointToScreen(p, textInput);
                                textPopupMenu.setLocation(p.x, p.y + 20);
                            }
                            else
                            {
                                textPopupMenu.show(textInput, p.x, p.y + 20);
                            }
                        }
                    };

                    textInput.addKeyListener(textInputListener);
                    new JFrame("TEST")
                        {

                            {
                                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                add(textInput);
                                setSize(400, 60);
                                setLocationRelativeTo(null);
                                setVisible(true);
                            }
                        };
                }
                ;
            });
    }
}

回答by Hendy Irawan

You can use JEdit's textareawith built-in completion & syntax highlighting framework.

您可以将JEdi​​t 的 textarea与内置完成和语法高亮框架一起使用。

A more heavyweight solution (that is good on the long term) is use NetBeans Platform.

一个更重量级的解决方案(从长远来看是好的)是使用NetBeans Platform

回答by pek

Here is a great article that uses a couple of libraries: Adding Auto-Complete Support to Swing Comboboxes@Java.net

这是一篇使用几个库的很棒的文章:将自动完成支持添加到 Swing Comboboxes@Java.net

回答by Maciej Modelski

You can use this library: http://fifesoft.com/autocomplete/

你可以使用这个库:http: //fifesoft.com/autocomplete/