29

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).

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

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

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
Geo
  • 93,257
  • 117
  • 344
  • 520

8 Answers8

13

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

http://swinglabs.org

Edit: This site seems to have moved 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

Geekygecko
  • 3,942
  • 2
  • 25
  • 21
  • 2
    Notice that the swinglabs site now appears empty. However, there is https://swinglabs.dev.java.net, which gives access to the sources. Furthermore, the project seems to be avaiable via maven, like http://www.mvnbrowser.com/artifact-details.html?groupId=org.swinglabs&artifactId=swingx&version=0.9.5-2&tab=VERSIONS#tabs indicates. – Riduidel Nov 04 '09 at 08:42
  • It is also available on Maven Central http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.swinglabs.swingx%22 – ftraian Jun 26 '14 at 07:48
11

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

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!

ivan_ivanovich_ivanoff
  • 19,113
  • 27
  • 81
  • 100
7

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
  }

}
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
ivan_ivanovich_ivanoff
  • 19,113
  • 27
  • 81
  • 100
  • Ah! I've figured out what's wrong! 1) Just ignore the caret position when the text field is empty! 2) Use instead of KeyListener something such as UndoableEditListener. – ivan_ivanovich_ivanoff Jun 22 '09 at 23:32
3

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

pek
  • 17,847
  • 28
  • 86
  • 99
3

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

1

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

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

Hendy Irawan
  • 20,498
  • 11
  • 103
  • 114
0

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);
                            }
                        };
                }
                ;
            });
    }
}
Alfabravo
  • 7,493
  • 6
  • 46
  • 82
0

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

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

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130