Autocomplete in JComboBox

Hey folks,
I want to enable autocomplete in a simple editable JComboBox (like in MS access). I've been searching google and now here, but cant seem to find anything. Does anyone have any idea how to implement this?
Furthermore: i cant seem to capture keys being pressed in the editable combobox. It wont fire keypressed/released/typed events when i type in the box :( Are any events fired at all when one types a(ny) key in a JComboBox?? (that is, every time a key is pressed, so the the actionPerformed when you hit enter won't do)
Any help greatly appreciated!

Hello,
my old attempt could help you:
package temp;
* AutoCompleteComboBox.java
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import javax.swing.text.*;
public class AutoCompleteComboBox extends JComboBox
     private static final Locale[] INSTALLED_LOCALES = Locale.getAvailableLocales();
     private ComboBoxModel model = null;
     public static void main(String[] args)
          JFrame f = new JFrame("AutoCompleteComboBox");
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          AutoCompleteComboBox box = new AutoCompleteComboBox(INSTALLED_LOCALES, false);
          f.getContentPane().add(box);
          f.pack();
          f.setLocationRelativeTo(null);
          f.setVisible(true);
      * Constructor for AutoCompleteComboBox -
      * The Default Model is a TreeSet which is alphabetically sorted and doesnt allow duplicates.
      * @param items
     public AutoCompleteComboBox(Object[] items, boolean caseSensitive)
          super(items);
          model = new ComboBoxModel(items);
          setModel(model);
          setEditable(true);
          setEditor(new AutoCompleteEditor(this, caseSensitive));
      * Constructor for AutoCompleteComboBox -
      * The Default Model is a TreeSet which is alphabetically sorted and doesnt allow duplicates.
      * @param items
     public AutoCompleteComboBox(Vector items, boolean caseSensitive)
          super(items);
          model = new ComboBoxModel(items);
          setModel(model);
          setEditable(true);
          setEditor(new AutoCompleteEditor(this, caseSensitive));
      * Constructor for AutoCompleteComboBox -
      * This constructor uses JComboBox's Default Model which is a Vector.
      * @param caseSensitive
     public AutoCompleteComboBox(boolean caseSensitive)
          super();
          setEditable(true);
          setEditor(new AutoCompleteEditor(this, caseSensitive));
      * ComboBoxModel.java
     public class ComboBoxModel extends DefaultComboBoxModel
           * The TreeSet which holds the combobox's data (ordered no duplicates)
          private TreeSet values = null;
          public ComboBoxModel(List items)
               super();
               this.values = new TreeSet();
               int i, c;
               for (i = 0, c = items.size(); i < c; i++)
                    values.add(items.get(i).toString());
               Iterator it = values.iterator();
               while (it.hasNext())
                    super.addElement(it.next().toString());
          public ComboBoxModel(final Object items[])
               this(Arrays.asList(items));
      * AutoCompleteEditor.java
     public class AutoCompleteEditor extends BasicComboBoxEditor
          public AutoCompleteEditor(JComboBox combo, boolean caseSensitive)
               super();
               editor = new AutoCompleteEditorComponent(combo, caseSensitive);
      * AutoCompleteEditorComponent.java
     public class AutoCompleteEditorComponent extends JTextField
          JComboBox combo = null;
          boolean caseSensitive = false;
          public AutoCompleteEditorComponent(JComboBox combo, boolean caseSensitive)
               super();
               this.combo = combo;
               this.caseSensitive = caseSensitive;
           * overwritten to return custom PlainDocument which does the work
          protected Document createDefaultModel()
               return new PlainDocument()
                    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
                         if (str == null || str.length() == 0)
                              return;
                         int size = combo.getItemCount();
                         String text = getText(0, getLength());
                         for (int i = 0; i < size; i++)
                              String item = combo.getItemAt(i).toString();
                              if (getLength() + str.length() > item.length())
                                   continue;
                              if (!caseSensitive)
                                   if ((text + str).equalsIgnoreCase(item)||item.substring(0, getLength() + str.length()).equalsIgnoreCase(text + str))
                                        combo.setSelectedIndex(i);
                                         super.remove(0, getLength());
                                        super.insertString(0, item, a);
                                        return;
                              else if (caseSensitive)
                                   if ((text + str).equals(item)||item.substring(0, getLength() + str.length()).equals(text + str))
                                        combo.setSelectedIndex(i);
                                        super.remove(0, getLength());
                                        super.insertString(0, item, a);
                                        return;
}The relevant part is the insertString method, i must admit not really simple.
Regards,
Tim

Similar Messages

  • JComboBox AutoCompleteDecorator & MouseClicked event

    Hi, I have a problem with a JComboBox's MouseClicked.
    I have imported an AutoCompleteDecorator to my combobox but, because of this, whenever I double click on the combo, it doesn't fire an event.
    To get it to fire an event, I have to click exactly on the combobox's border,which is qiute a hastle. Is there a work around for this or another way to implement autocomplete?

    I've also created a different class that does the same thing, AND still gives me the same problem.
    package oma;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    * @author Zweli
    public class AutoComplete extends JComboBox implements JComboBox.KeySelectionManager{
        private String searchFor;
         private long lap;
         public class CBDocument extends PlainDocument {
                public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
                    if (str==null) return;
              super.insertString(offset, str, a);
                        if(!isPopupVisible() && str.length() != 0) fireActionEvent();
        public AutoComplete(Object[] items) {
            super(items);
         lap = new java.util.Date().getTime();
         setKeySelectionManager(this);
         JTextField tf;
         if(getEditor() != null) {
                tf = (JTextField)getEditor().getEditorComponent();
                if(tf != null) {
                    tf.setDocument(new CBDocument());
                    addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            JTextField tf = (JTextField)getEditor().getEditorComponent();
                            String text = tf.getText();
                            ComboBoxModel aModel = getModel();
                            String current;
                            for (int i = 0; i < aModel.getSize(); i++) {
                                current = aModel.getElementAt(i).toString();
                                if(current.toLowerCase().startsWith(text.toLowerCase())) {
                                    tf.setText(current);
                                    tf.setSelectionStart(text.length());
                        tf.setSelectionEnd(current.length());
                        break;
        public int selectionForKey(char aKey, ComboBoxModel aModel) {
         long now = new java.util.Date().getTime();
            if (searchFor!=null && aKey==KeyEvent.VK_BACK_SPACE &&     searchFor.length()>0) {
                searchFor = searchFor.substring(0, searchFor.length() -1);
            } else {
                //     System.out.println(lap);
                // Kam nie hier vorbei.
                if(lap + 1000 < now)
                    searchFor = "" + aKey;
                else
                    searchFor = searchFor + aKey;
         lap = now;
         String current;
         for(int i = 0; i < aModel.getSize(); i++) {
                current = aModel.getElementAt(i).toString().toLowerCase();
                if (current.toLowerCase().startsWith(searchFor.toLowerCase())) return i;
            return -1;
        public void fireActionEvent() {
            super.fireActionEvent();
    }Thanx, Zweli

  • How can I bind a component to ADF?

    Hi all!
    I'm really new to OOP, Java, and JDeveloper. I managed to create a small ADF Swing application successfully through the wizards, help files, and examples.
    I want to incorporate the components of SwingX into it, specifically having auto-completion in my combobox.
    I did the following:
    import org.jdesktop.swingx.autocomplete.Configurator;
    JComboBox mycomboBox = [...];
    Configurator.enableAutoCompletion(mycomboBox);
    but when I run the form, mycombobox just displays "oracle.jbo.server.ViewRowImpl@2" and it doesn't auto-complete.
    Searching the forums, Erik said "If you are trying to bind the component using ADF, then you will have to create your own custom binding class. Depending on the component's needs, you might start with adapting the JUTextFieldBinding to work with your component.".
    Can someone point me to a "HOW-TO" guide for the above, esp. code samples etc...
    Thanks.

    Unfortunately, the solution is very complicated due to the way the JUComboboxBinding is implemented. It doesn't require a custom ADF binding class, however.
    I'll see if we are able to provide some of the pieces needed to duplicate what we have done to use SwingX auto-completion.
    Erik
    P.S. Let me know if you need to use a SwingX JXTreeTable. We do have a custom binding class for it that we should be able to share.

  • ComboBox doesnt auto-select items

    Hello,
    my AutoCompleteComboBox doesnt autoselect the first item after initializing and doesnt recognize if user clicks on an item in the list.
    I thought every combobox has an actionlistner therefor.
    I'm using custom editor-component and model but i dont know where i could have done something wrong.
    Any suggestions ?
    * AutoCompleteComboBox.java
    import java.awt.Component;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.BasicComboBoxEditor;
    import javax.swing.text.*;
    public class AutoCompleteComboBox extends JComboBox
         private static final Locale[] INSTALLED_LOCALES = Locale.getAvailableLocales();
         private ComboBoxModel model = null;
         public static void main(String[] args)
              JFrame f = new JFrame("AutoCompleteComboBox");
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              AutoCompleteComboBox box = new AutoCompleteComboBox(INSTALLED_LOCALES, false);
              f.getContentPane().add(box);
              f.pack();
              f.setLocationRelativeTo(null);
              f.setVisible(true);
          * Constructor for AutoCompleteComboBox -
          * The Default Model is a TreeSet which is alphabetically sorted and doesnt allow duplicates.
          * @param items
         public AutoCompleteComboBox(Object[] items, boolean caseSensitive)
              super(items);
              model = new ComboBoxModel(items);
              setModel(model);
              setEditable(true);
              setEditor(new AutoCompleteEditor(this, caseSensitive));
          * Constructor for AutoCompleteComboBox -
          * The Default Model is a TreeSet which is alphabetically sorted and doesnt allow duplicates.
          * @param items
         public AutoCompleteComboBox(Vector items, boolean caseSensitive)
              super(items);
              model = new ComboBoxModel(items);
              setModel(model);
              setEditable(true);
              setEditor(new AutoCompleteEditor(this, caseSensitive));
          * Constructor for AutoCompleteComboBox -
          * This constructor uses JComboBox's Default Model which is a Vector.
          * @param caseSensitive
         public AutoCompleteComboBox(boolean caseSensitive)
              super();
              setEditable(true);
              setEditor(new AutoCompleteEditor(this, caseSensitive));
          * ComboBoxModel.java
         public class ComboBoxModel extends DefaultComboBoxModel
               * The TreeSet which holds the combobox's data (ordered no duplicates)
              private TreeSet values = null;
              public ComboBoxModel(List items)
                   super();
                   this.values = new TreeSet();
                   int i, c;
                   for (i = 0, c = items.size(); i < c; i++)
                        values.add(items.get(i).toString());
                   Iterator it = values.iterator();
                   while (it.hasNext())
                        super.addElement(it.next().toString());
              public ComboBoxModel(final Object items[])
                   this(Arrays.asList(items));
          * AutoCompleteEditor.java
         public class AutoCompleteEditor extends BasicComboBoxEditor
              private JTextField editor = null;
              public AutoCompleteEditor(JComboBox combo, boolean caseSensitive)
                   super();
                   this.editor = new AutoCompleteEditorComponent(combo, caseSensitive);
               * overrides BasicComboBox's getEditorComponent to return custom TextField (AutoCompleteEditorComponent)
              public Component getEditorComponent()
                   return editor;
          * AutoCompleteEditorComponent.java
         public class AutoCompleteEditorComponent extends JTextField
              JComboBox combo = null;
              boolean caseSensitive = false;
              public AutoCompleteEditorComponent(JComboBox combo, boolean caseSensitive)
                   super();
                   this.combo = combo;
                   this.caseSensitive = caseSensitive;
               * overwritten to return custom PlainDocument which does the work
              protected Document createDefaultModel()
                   return new PlainDocument()
                        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
                             if (str == null || str.length() == 0)
                                  return;
                             int size = combo.getItemCount();
                             String text = getText(0, getLength());
                             for (int i = 0; i < size; i++)
                                  String item = combo.getItemAt(i).toString();
                                  if (getLength() + str.length() > item.length())
                                       continue;
                                  if (!caseSensitive)
                                       if ((text + str).equalsIgnoreCase(item))
                                            combo.setSelectedIndex(i);
                                            if (!combo.isPopupVisible())
                                                 combo.setPopupVisible(true);
                                            super.remove(0, getLength());
                                            super.insertString(0, item, a);
                                            return;
                                       else if (item.substring(0, getLength() + str.length()).equalsIgnoreCase(text + str))
                                            combo.setSelectedIndex(i);
                                            if (!combo.isPopupVisible())
                                                 combo.setPopupVisible(true);
                                            super.remove(0, getLength());
                                            super.insertString(0, item, a);
                                            return;
                                  else if (caseSensitive)
                                       if ((text + str).equals(item))
                                            combo.setSelectedIndex(i);
                                            if (!combo.isPopupVisible())
                                                 combo.setPopupVisible(true);
                                            super.remove(0, getLength());
                                            super.insertString(0, item, a);
                                            return;
                                       else if (item.substring(0, getLength() + str.length()).equals(text + str))
                                            combo.setSelectedIndex(i);
                                            if (!combo.isPopupVisible())
                                                 combo.setPopupVisible(true);
                                            super.remove(0, getLength());
                                            super.insertString(0, item, a);
                                            return;
    }regards,
    Tim

    Hallo Tim,
    I didn't thoroughly go through your code, but remembered a less
    complex piece of code which does its job nicely. Although its
    approach is somewhat different from yours (it doesn't care for
    the Combomodel and has no case-sensitivity implemented), it might
    nevertheless be of help.import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class AutoComplete extends JComboBox
                      implements JComboBox.KeySelectionManager {
      private String searchFor;
      private long lap;
      public class CBDocument extends PlainDocument {
        public void insertString(int offset, String str, AttributeSet a)
                             throws BadLocationException {
          if (str==null) return;
          super.insertString(offset, str, a);
          if(!isPopupVisible() && str.length() != 0) fireActionEvent();
      public AutoComplete(Object[] items) {
        super(items);
        lap = new java.util.Date().getTime();
        setKeySelectionManager(this);
        JTextField tf;
        if(getEditor() != null) {
          tf = (JTextField)getEditor().getEditorComponent();
          if(tf != null) {
            tf.setDocument(new CBDocument());
            addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent evt) {
                JTextField tf = (JTextField)getEditor().getEditorComponent();
                String text = tf.getText();
                ComboBoxModel aModel = getModel();
                String current;
                for(int i = 0; i < aModel.getSize(); i++) {
                  current = aModel.getElementAt(i).toString();
                  if(current.toLowerCase().startsWith(text.toLowerCase())) {
                    tf.setText(current);
                    tf.setSelectionStart(text.length());
                    tf.setSelectionEnd(current.length());
              break;
      public int selectionForKey(char aKey, ComboBoxModel aModel) {
        long now = new java.util.Date().getTime();
        if (searchFor!=null && aKey==KeyEvent.VK_BACK_SPACE &&
         searchFor.length()>0) {
          searchFor = searchFor.substring(0, searchFor.length() -1);
        else {
    //     System.out.println(lap); // Kam nie hier vorbei.
          if(lap + 1000 < now)
            searchFor = "" + aKey;
          else
            searchFor = searchFor + aKey;
        lap = now;
        String current;
        for(int i = 0; i < aModel.getSize(); i++) {
          current = aModel.getElementAt(i).toString().toLowerCase();
          if (current.toLowerCase().startsWith(searchFor.toLowerCase())) return i;
        return -1;
      public void fireActionEvent() {
        super.fireActionEvent();
      public static void main(String arg[]) {
        JFrame f = new JFrame("AutoCompleteComboBox");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(200,300);
        Container cp= f.getContentPane();
        cp.setLayout(null);
        String[] names= {"Beate", "Claudia", "Fjodor", "Fred", "Friedrich",
         "Fritz", "Frodo", "Hermann", "Willi"};
        JComboBox cBox= new AutoComplete(names);
    //    Locale[] locales = Locale.getAvailableLocales();
    //    JComboBox cBox= new AutoComplete(locales);
        cBox.setBounds(50,50,100,21);
        cBox.setEditable(true);
        cp.add(cBox);
        f.setVisible(true);
    }Greetings
    Joerg

  • Stopping cell editing in a JTable using a JComboBox editor w/ AutoComplete

    Hi there! Me again with more questions!
    I'm trying to figure out the finer parts of JTable navigation and editing controls. It's getting a bit confusing. The main problem I'm trying to solve is how to make a JTable using a combo box editor stop editing by hitting the 'enter' key in the same fashion as a JTextField editor. This is no regular DefaultCellEditor though -- it's one that uses the SwingX AutoCompleteDecorator. I have an SSCCE that demonstrates the issue:
    import java.awt.Component;
    import java.awt.EventQueue;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableModel;
    import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
    public class AutoCompleteCellEditorTest extends JFrame {
      public AutoCompleteCellEditorTest() {
        JTable table = new JTable();
        Object[] items = {"A", "B", "C", "D"};
        TableModel tableModel = new DefaultTableModel(2, 2);
        table.setModel(tableModel);
        table.getColumnModel().getColumn(0).setCellEditor(new ComboCellEditor(items));
        getContentPane().add(table);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        pack();
      private class ComboCellEditor extends AbstractCellEditor implements TableCellEditor {
        private JComboBox comboBox;
        public ComboCellEditor(Object[] items) {
          this.comboBox = new JComboBox(items);
          AutoCompleteDecorator.decorate(this.comboBox);
        public Object getCellEditorValue() {
          return this.comboBox.getSelectedItem();
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
          comboBox.setSelectedItem(value);
          return comboBox;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            new AutoCompleteCellEditorTest().setVisible(true);
    }Problem 1: Starting to 'type' into the AutoCompleteDecorate combo box doesn't cause it to start editing. You have to hit F2, it would appear. I've also noticed this behaviour with other JComboBox editors. Ideally that would be fixed too. Not sure how to do this one.
    Problem 2: After editing has started (say, with the F2 key), you may start typing. If you type one of A, B, C, or D, the item appears. That's all good. Then you try to 'complete' the edit by hitting the 'enter' key... and nothing happens. The 'tab' key works, but it puts you to the next cell. I would like to make the 'enter' key stop editing, and stay in the current cell.
    I found some stuff online suggesting you take the input map of the table and set the Enter key so that it does the same thing as tab. Even though that's not exactly what I desired (I wanted the same cell to be active), it didn't work anyway.
    I also tried setting a property on the JComboBox that says that it's a table cell editor combo box (just like the DefaultCellEditor), but that didn't work either. I think the reason that fails is because the AutoCompleteDecorator sets isEditable to true, and that seems to stop the enter key from doing anything.
    After tracing endless paths through processKeyBindings calls, I'm not sure I'm any closer to a solution. I feel like this should be a fairly straightforward thing but I'm having a fair amount of difficulty with it.
    Thanks for any direction you can provide!

    Hi Jeanette,
    Thanks for your advice. I looked again at the DefaultCellEditor. You are correct that I am not firing messages for fireEditingStopped() and fireEditingCancelled(). Initially I had copied the behaviour from DefaultCellEditor but had trimmed it out. I assumed that since I was extending AbstractCellEditor and it has them implemented correctly that I was OK. But I guess that's not the case! The problem I'm having with implementing the Enter key stopping the editing is that:
    1) The DefaultCellEditor stops cell editing on any actionPerformed. Based on my tests, actionPerformed gets called whenever a single key gets pressed. I don't want to end the editing on the AutoCompleteDecorated box immediately -- I'd like to wait until the user is happy with his or her selection and has hit 'Enter' before ending cell editing. Thus, ending cell editing within the actionPerformed listener on the JComboBox (or JXComboBox, as I've made it now) will not work. As soon as you type a single key, if it is valid, the editing ends immediately.
    2) I tried to add a key listener to the combo box to pick up on the 'Enter' key and end the editing there. However, it appears that the combo box does not receive the key strokes. I guess they're going to the AutoCompleteDecorator and being consumed there so the combo box does not receive them. If I could pick up on the 'Enter' key there, then that would work too.
    I did more reading about input maps and action maps last night. Although informative, I'm not sure how far it got me with this problem because if the text field in the AutoCompleteDecorator takes the keystroke, I'm not sure how I'm going to find out about it in the combo box.
    By the way, when you said 'They are fixed... in a recent version of SwingX', does that mean 1.6.2? That's what I'm using.
    Thanks!
    P.S. - Maybe I should create a new question for this? I wanted to mark your answer as helpful but I already closed the thread by marking the answer to the first part as correct. Sorry!
    Edited by: aardvarkk on Jan 27, 2011 7:41 AM - Added SwingX versioning question.

  • JComboBox autocomplete problem

    hi all. I would like to know a, quick, easy and simple technique to have auto complete function in JComboBox.
    I know this question about autocomplete has been answered several times in this forum. But all of them give some complex custom made codes.
    Since this is a very nice feature in Windows, doesnt Java provide support for this in one of its API?
    I have gone through the documentation also to find whether this function has been already implemented. Apparently, I could not find such support. Could anyone please give me any guidance.
    thanks.

    If Java supported this in the standard API's, then you wouldn't find "complex custom made codes" around here, you'd find people telling others to check out this or that class or method.

  • Implementation of Autocomplete JComboBox in an applet

    Can anybody help me in this problem:
    A autocomplete JComboBox when integrated with an applet the key listener registered to the text editor of the JComboBox is not listening.Can anbody tell me why, it is not happening.
    Thanks in advance.

    Try this approach: http://www.orbital-computer.de/JComboBox

  • AutoComplete JComboBox As JTable cell editor

    Hello, when I try to use AutoComplete JComboBox as my JTable cell editor, I facing the following problem
    1) Exception thrown when show pop up. - Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    2) Unable to capture enter key event.
    Here is my complete working code. With the same JComboBox class, I face no problem in adding it at JFrame. But when using it as JTable cell editor, I will have the mentioned problem.
    Any advice? Thanks
    import javax.swing.*;
    import javax.swing.JTable.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    * @author  yccheok
    public class NewJFrame extends javax.swing.JFrame {
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
                    /* Combo Box Added In JFrame. Work as expected. */
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    getContentPane().add(comboBox, java.awt.BorderLayout.SOUTH);
        public JTable getMyTable() {
            return new JTable() {
                 Combo Box Added In JTable as cell editor. Didn't work as expected:
                 1. Exception thrown when show pop up.
                 2. Unable to capture enter key event.
                public TableCellEditor getCellEditor(int row, int column) {
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    return new DefaultCellEditor(comboBox);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = getMyTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration                  
    }

    You need to create a custom CellEditor which will prevent these problems from occurring. The explanation behind the problem and source code for the new editor can be found at Thomas Bierhance's site http://www.orbital-computer.de/JComboBox/. The description of the problem and the workaround are at the bottom of the page.

  • JComboBox - autocomplete

    Hello everyone!
    I wrote a piece of code that makes a JComboBox work autocomplete. It's working fine but not when I set the look and feel as a system look and feel - not java look and feel. If you're gonna read the code trying to help me, you're gonna see, that if the user types in the combo box some character, the text gets highlited. In the java look and feel it doesn't. So the highliting is only tisturbing the functionality of the combo box.
    Any suggestions?
    Thanks for future help!
    The code:
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.util.Vector;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.UIManager;
    class Testing extends JFrame {
        JComboBox jcb = null;
        Vector<String> v = null;
        public Testing() {
            this.getContentPane().setLayout(null);
            this.setLocation(300, 30);
            this.setSize(300, 300);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            v = new Vector<String>();
            v.add("tlakovanje");
            v.add("tlakovec");
            v.add("tlakovana cesta");
            v.add("tla&#269;an");
            v.add("tlaka");
            v.add("slovenec");
            v.add("slovenka");
            v.add("slovenija");
            v.add("slovar");
            v.add("slovenci");
            v.add("&#269;ajra");
            v.add("&#269;aranje");
            jcb = new JComboBox();
            jcb.setEditable(true);
            jcb.setSelectedItem("");
            for (int i = 0; i < v.size(); i++) {
                jcb.addItem(v.get(i));
            jcb.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() != 38 && e.getKeyCode() != 40 && e.getKeyCode() != 10) {
                    String a = jcb.getEditor().getItem().toString();
                    jcb.removeAllItems();
                    int st = 0;
                    for (int i = 0; i < v.size(); i++) {
                        if (v.get(i).startsWith(a)) { jcb.addItem(v.get(i)); st++; }
                    jcb.getEditor().setItem(new String(a));
                    jcb.hidePopup();
                    if (st != 0) { jcb.showPopup(); }
            jcb.setBounds(20, 20, 150, 20);
            this.getContentPane().add(jcb);
            this.setVisible(true);
        public static void main(String[] args) {
            UIManager.LookAndFeelInfo[] l = UIManager.getInstalledLookAndFeels();
            try {
                UIManager.setLookAndFeel(l[0].getClassName());
            } catch (Exception e) {
                e.printStackTrace();
            Testing testing;
            testing = new Testing();
    }Tilen

    OOhhhh shit .. it really works :) !!! Thanks dude! I was searching and searching for this caret trick but I didn't know how to do it cause the item that's set on the combo box editor actually wasn't a JTextField. It was just an object that I had to cast into an JTextField.
    And sorry ... gonna look the themes next time to post into the right one :).
    Thanks alot dude ;).

  • How do you set the number of visible items in the popup box of a JComboBox?

    Hi,
    Do you know how to set the number of items that shall be visible in the popup box of a JComboBox?
    I have produced an implementation of an autocomplete JComboBox such that following each character typed in the text field, the popup box is repopulated with items. Normally 8 items are visible when showing the popup box. Sometimes even though the list of items is > 8 the popup box shrinks in height so that 8 items are not visible.
    Thanks,
    Simon

    Below is my JComboBox autocomplete implementation.
    The problem seems to occur when the list of items is reduced in number, the button selected and then the list size increased, the popup box does not automatically increase in size. I have tried setMaximumRowCount � but does not resolve the problem.
    To see how it works:
    1)     click in text field.
    2)     Type 1 � the full list of items are shown.
    3)     Type 0 � the list has been narrowed down � the popup box is greyed out for remaining items.
    4)     Type Backspace � the full list of items is redisplayed.
    5)     Type 0 � to narrow down the list.
    6)     Select button � the popup box is invisible.
    7)     Select button � the popup box is displayed with 2 items.
    8)     Select Backspace � here is the problem � the combo box list contains all items but the popup box has been shrunk so that only 2 are visible.
    9)     Select button � popup box is invisible.
    10)     Select button � popup box is as expected.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.Enumeration;
    import java.util.Vector;
    import javax.swing.plaf.basic.*;
    class Test
    private JComboBox jCB = null;
    private JTextField jTF=null;
    private String typed="";
    private Vector vector=new Vector();
    public Test()
    JFrame fr=new JFrame("TEST ComboBox");
    JPanel p = new JPanel();
    p.setLayout( new BorderLayout() );
    ComboBoxEditor anEditor = new BasicComboBoxEditor();
    String[] s = new String[30];
    for (int i=0; i<30; i++) {
    s[i] = (new Integer(i+10)).toString();
    jTF=(JTextField)anEditor.getEditorComponent();
    jTF.addKeyListener(new KeyAdapter()
    public void keyReleased( KeyEvent ev )
    char key=ev.getKeyChar();
    if (! (Character.isLetterOrDigit(key)
    ||Character.isSpaceChar(key)
    || key == KeyEvent.VK_BACK_SPACE )) return;
    typed="";
    typed=jTF.getText();
    fillCB(vector);
    jCB.showPopup();
    jCB = new JComboBox();
    jCB.setEditor(anEditor);
    jCB.setEditable(true);
    boolean ins;
    for (int x=0; x<30; x++)
    ins = vector.add( new String(s[x]) );
    fillCB(vector);
    jCB.setSelectedIndex(-1);
    fr.getContentPane().add(p);
    p.add("South",jCB);
    p.add("Center",new JButton("test combo box"));
    fr.pack();
    fr.show();
    public void fillCB(Vector vector)
    typed = typed.trim();
    String typedUp = typed.toUpperCase();
    jCB.removeAllItems();
    jCB.addItem("Please select");
    for(Enumeration enu = vector.elements(); enu.hasMoreElements();) {
    String s = (String)enu.nextElement();
    if (s.toUpperCase().startsWith(typedUp)) {
    jCB.addItem(s);
    jTF.setText(typed);
    public static void main( String[] args )
    Test test=new Test();
    Many thanks,
    Simon

  • Combobox Autocomplete editor inside Jtable cell

    I have a custom combobox editor which supports the autocomplete feature as follows:
    as soon as the user keys in any character, this editor searches for the item that starts with keyed in character. This item is displayed in the editor text field and the combobox popup is set to visible and the this item is set to selected.
    this editor works fine when standalone. but the popup fails to become visible when this combobox is used as an celleditor inside jtable. infact the focus is lost from the entire table.
    can anyone suggest the possible reason (and solution if possible).
    following are the code snippets for the same: -
         private TableCellEditor addCellEditor() {
              final JComboBox myJComboBox = new PIComboBox();
              myJComboBox.setModel(new DefaultComboBoxModel(// some data model //));
              //change the size of popup window
              BasicComboPopup comboPopup = null;
              for (int i=0, n=getUI().getAccessibleChildrenCount(myJComboBox); i<n; i++) {
                  Object component = getUI().getAccessibleChild(myJComboBox, i);
                  if (component instanceof BasicComboPopup) {
                   comboPopup = (BasicComboPopup) component;
                   break;
              if(null != comboPopup)
                  comboPopup.setLayout(new GridLayout(1,1));
                  comboPopup.setPopupSize(new Dimension(200, 150));
              myJComboBox.setEditable(true);
              myJComboBox.setEditor(new ComboBoxAutoCompleteEditor(myJComboBox, 3));
              myJComboBox.setUI(new ComboBoxAutoCompleteUI());
              TableCellEditor myCellEditor = new DefaultCellEditor(myJComboBox );
              return myCellEditor;
         public class ComboBoxAutoCompleteEditor extends BasicComboBoxEditor {
         public ComboBoxAutoCompleteEditor(PIComboBox comboBox, int maxLength) {
              super();
              this.comboBox = comboBox;
              this.maxLength = maxLength;
         @Override
         public Component getEditorComponent() {
              if(null == editorComponent)
                   editorComponent = new PITextField();
                   editorComponent.setBorder(null);
                   editorComponent.setMaxLength(maxLength);
                   editorComponent.setDocument(getDocument());
              return editorComponent;
         private ComboBoxAutoCompleteDocument getDocument()
              if(null == comboBoxAutoCompleteDocument)
                   comboBoxAutoCompleteDocument = new ComboBoxAutoCompleteDocument(
                             this.comboBox.getModel());
                   comboBoxAutoCompleteDocument.addDocumentListener(new ComboBoxDocumentListener());
              return comboBoxAutoCompleteDocument;
         private class ComboBoxDocumentListener implements DocumentListener {
              public void insertUpdate(DocumentEvent e) {
                   if (updatingSelection) {
                        return;
                   SwingUtilities.invokeLater(new ScrollHandler());
              public void removeUpdate(DocumentEvent e) {
              public void changedUpdate(DocumentEvent e) {
         private class ScrollHandler implements Runnable {
              private String scrollToString;
              private int scrollToRow;
              private ScrollHandler() {
                   try {
                        int length = getDocument().getLength();
                        String text = getDocument().getText(0, length);
                        scrollToRow = -1;
                        scrollToString = (String) comboBox.getSelectedItem();
                        ComboBoxModel model = comboBox.getModel();
                        int size = model.getSize();
                        for (int i = 0;  i < size; i++) {
                             String item = model.getElementAt(i).toString();
                             if (item.startsWith(text)) {
                                  scrollToString = item;
                                  break;
                             scrollToRow++;
                   } catch (BadLocationException ble) {
                        // TODO: handle
                        ble.printStackTrace();
              public void run() {
                   final int matchCount = getDocument()
                             .getCurrentMatchCount();
                   updatingSelection = true;
                   comboBox.setSelectedItem(scrollToString);
                   if (comboBox.isDisplayable())
                        comboBox.showPopup();
                   updatingSelection = false;
                   if (scrollToRow != comboBox.getItemCount() - 1) {
                        ComboBoxAutoCompleteUI ui = (ComboBoxAutoCompleteUI) comboBox
                                  .getUI();
                        JList popupList = ui.getPopupList();
                        int rowsToAdd = Math.min(comboBox.getMaximumRowCount(), comboBox
                                  .getItemCount()
                                  - scrollToRow - 1);
                        popupList.scrollRectToVisible(popupList.getCellBounds(
                                  scrollToRow + rowsToAdd, scrollToRow + rowsToAdd));
                   if (matchCount > 0) {
                        ((PITextField)getEditorComponent()).setSelectionStart(matchCount);
                        ((PITextField)getEditorComponent()).setSelectionEnd(
                                  getDocument().getLength());
         public class ComboBoxAutoCompleteUI extends BasicComboBoxUI {
             JList getPopupList() {
                 return popup.getList();
         public class ComboBoxAutoCompleteDocument extends PlainDocument {
         public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            currentMatchCount = getLength() + str.length();
            String currentText = getText(0, getLength());
            //search the matching string here
            offs = 0;
            remove(0, getLength());
            super.insertString(offs, str, a);
         **************

    You need to create a custom CellEditor which will prevent these problems from occurring. The explanation behind the problem and source code for the new editor can be found at Thomas Bierhance's site http://www.orbital-computer.de/JComboBox/. The description of the problem and the workaround are at the bottom of the page.

  • Editable JComboBox in a JTable

    I posted my problem into the "Java Essentials/Java programming" forum but it would be much better if I'd posted it here into the swing theme :).
    Here it is what I posted:
    Funky_1321
    Posts:8
    Registered: 2/22/06
    editable JComboBox in a JTable
    Oct 21, 2006 1:32 PM
    Click to email this message
    Hello!
    Yesterday I posted a problem, solved it and there's another one, referring the same theme.
    So it's about a editable JComboBox with autocomplete function. The combo is a JTables cellEditors component. So it's in a table. So when the user presses the enter key to select an item from the JComboBox drop down menu, I can't get which item is it, not even which index has the item in the list. If for exemple the JComboBox isn't in a table but is added on a JPanel, it works fine. So I want to get the selectedItem in the actionPerformed method implemented in the combo box. I always get null instead of the item.
    Oh... if user picks up some item in the JComboBox-s list with the mouse, it's working fine but I want that it could be picked up with the enter key.
    Any solutions appreciated!
    Thanks, Tilen
    YAT_Archivist
    Posts:1,321
    Registered: 13/08/05
    Re: editable JComboBox in a JTable
    Oct 21, 2006 1:55 PM (reply 1 of 2)
    Click to email this message
    I suggest that you distill your current code into a simple class which has the following attributes:
    1. It can be copied and pasted and will compile straight out.
    2. It has a main method which brings up a simple example frame.
    3. It's no more than 50 lines long.
    4. It demonstrates accurately what you've currently got working.
    Without that it's hard to know exactly what you're currently doing, and requires a significant investment of time for someone who hasn't already solved this problem before to attempt to help. I'm not saying that you won't get help if you don't post a simple demo class, but it will significantly improve your chances.
    Funky_1321
    Posts:8
    Registered: 2/22/06
    Re: editable JComboBox in a JTable
    Oct 21, 2006 2:11 PM (reply 2 of 2)
    Click to email this message
    Okay ... I'll write the code in short format:
    class acJComboBox extends JComboBox {
      public acJComboBox() {
        this.setEditable(true);
        this.setSelectedItem("");
        this.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) {
         // ... code code code
         // that's tricky ... the method getSelectedItem() always returns null - remember; the acJComboBox is in a JTable!
         if (e.getKeyCode() == 10 && new String((String)getEditor().getItem()).length() != 0) { getEditor().setItem(getSelectedItem()); }
    }And something more ... adding the acJComboBox into the JTable:
    TableColumn column = someTable.getColumn(0);
    column.setCellEditor(new DefaultCellEditor(new acJComboBox());
    So if the user presses the enter key to pick up an item in the combo box drop down menu, it should set the editors item to the selected item from the drop down menu (
    getEditor().setItem(getSelectedItem());
    When the acJComboBox is on a usual JPanel, it does fine, but if it's in the JTable, it doesn't (getSelectedItem() always returns null).
    Hope I described the problem well now ;).

    Okay look ... I couldn't write a shorter code just for an example. I thought that my problem could be understoodable just in mind. However ... type in the first combo box the letter "i" and then select some item from the list with pressing the enter key. Do the same in the 2nd combo box who's in the JTable ... the user just can't select that way if the same combo is in the JTable. Why? Thanks alot for future help!
    the code:
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Vector;
    import javax.swing.DefaultCellEditor;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    class Example extends JFrame {
        private String[] columns = { "1", "2", "3" };
        private String[][] rows = {};
        private DefaultTableModel model = new DefaultTableModel(rows, columns);
        private JTable table = new JTable(model);
        private JScrollPane jsp = new JScrollPane(table);
        private acJComboBox jcb1 = new acJComboBox();
        private acJComboBox jcb2 = new acJComboBox();
        public Example() {
            // initialize JFrame
            this.setLayout(null);
            this.setLocation(150, 30);
            this.setSize(300, 300);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            // initialize JFrame
            // initialize components
            Vector<String> v1 = new Vector<String>();
            v1.add("item1");
            v1.add("item2");
            v1.add("item3");
            jcb1.setData(v1);
            jcb2.setData(v1);
            jcb1.setBounds(30, 30, 120, 20);
            jsp.setBounds(30, 70, 250, 100);
            add(jcb1);
            add(jsp);
            TableColumn column = table.getColumnModel().getColumn(0);
            column.setCellEditor(new DefaultCellEditor(jcb2));
            Object[] data = { "", "", "" };
            model.addRow(data);
            // initialize components
            this.setVisible(true);
        public static void main(String[] args) {
            Example comboIssue = new Example();
    class acJComboBox extends JComboBox {
        private Vector<String> data = new Vector<String>();
        private void init() {
            this.setEditable(true);
            this.setSelectedItem("");
            this.setData(this.data);
            this.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) {
                        if (e.getKeyCode() != 38 && e.getKeyCode() != 40) {
                            String a = getEditor().getItem().toString();
                            setModel(new DefaultComboBoxModel());
                            int st = 0;
                            for (int i = 0; i < getData().size(); i++) {
                                String str1 = a.toUpperCase();
                                String tmp = (String)getData().get(i).toUpperCase();
                                if (str1.length() <= tmp.length()) {
                                    String str2 = tmp.substring(0, str1.length());
                                    if (str1.equals(str2)) {
                                        DefaultComboBoxModel model = (DefaultComboBoxModel)getModel();
                                        model.insertElementAt(getData().get(i), getItemCount());
                                        st++;
                            getEditor().setItem(new String(a));
                            JTextField jtf = (JTextField)e.getSource();
                            jtf.setCaretPosition(jtf.getDocument().getLength());
                            hidePopup();
                            if (st != 0 && e.getKeyCode() != 10 && new String((String)getEditor().getItem()).length() != 0) { showPopup(); }
                            if (e.getKeyCode() == 10 && new String((String)getEditor().getItem()).length() != 0) { getSelectedItem(); }
                            if (new String((String)getEditor().getItem()).length() == 0) { whenEmpty(); }
            this.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) {
                hidePopup();
        // - constructors -
        public acJComboBox() {
            init();
        public acJComboBox(Vector<String> data) {
            this.data = data;
            init();
        // - constructors -
        // - interface -
        public void whenEmpty() { } // implement if needed
        public void setData(Vector<String> data) {
            this.data = data;
            for (int i = 0; i < data.size(); i++) {
                this.addItem(data.get(i));
        public Vector<String> getData() {
            return this.data;
        // - interface -
    }

  • Dynamic JCombobox for a very big database resulset

    I want to use a JCombobox or similar for selecting values from a big database resultset. I'm using an editable one with SwingX autocomplete decorator. My strategy is:
    * show only first Xs regs.
    * let the user to enter some text in the combobox and refine the search reloading the model.
    Someone have some sample code or know some components that do that.
    Or can point me to some implementation details?�
    A lot of thanks in advance,
    PD:
    I need something efficient that don't query database to much.

    what is the size of the table and how many lines are you going to delete?
    I would recommend you to delete only up to 5000 or 10000 records in one step.
    do 100 times.
    select *
              from
              into table itab.
              where
              up to 10.000 records.
    if ( itab is initial )
      exit.
    endif.
    delete ... from table itab.
    commit work.
    If this is still too slow, than you should create a secondary index with zone.
    You can drop the index after the deletion is finished.
    Siegfried

  • JCalendar and JcomboBox access with keyboard

    Hello guys, What can i do?, ive implemented a JComboBox (this have autocompletion, downloaded of http://www.orbital-computer.de/JComboBox/), and Jcalendar inside a JTable but the problem appear when i try access to typing/input with keyboard in a JComboBox (i cant), this only activate with a mouse, the same ocurr with the next cell (JCalendar), this only activate with a mouse.
    What i need to change in the source code??
    Thanks...

    i'm not sure what you mean by "HTML Access Keys/Keyboard Shortcuts", but your browser's shortcut keys should continue to work.

  • Outlook autocomplete cache stops working for multiple users at the same time

    Hi there
    Ever since we upgraded our Exchange 2010 to Exchange 2013 we have had problems with the autocomplete cache in Outlook 2010.
    We have 700 users and about once per week I get a call about the autocomplete cache. A few users are on cached mode, but most use online mode. The problem appears on both, but it can usually be corrected by /cleanautocompletecache.
    Granted, the autocomplete cache gets corrupted sometimes, but it seems to happen a lot for us. I have noticed that often more than one user experiences the problem at the same time, and, since the problem starting after upgrading Exchange, I suspect that
    the issue is with Exchange and not Outlook. Yesterday three users complained about the cache at the same time.
    I know how to get a broken cache going again - that is not the issue. The issue is keeping this from happening so often.
    Anyone out there able to help?
    Thanks!
    /Anders

    Hi ,
    Based on my knowledge , when you tried to send an email to a recipient in the same exchange organisation then the recipient address will be resolved in to legacy dn value and then that email will be delivered to destination mailbox by pointing towards to
    that legacy dn value.
    For the external recipients exchange user the smtp address to get it delivered.
    For your issue :
    Based upon the NDR message , we need to covert those values in to x500 format and add it to respective recipient mailbox as an x500 address.Then These erorrs will happen if the x500 value of the destination recipient is not available on it's maibox
    and that would be the cause of the NDR for most of the times.Some time as you said autocomplete cache would get corrupted on the client end but it is very rare.
    How to convert NDR to x500 address format :
    http://msexchangeguru.com/2012/03/15/x500/
    How to avoid getting such kind of NDR'S :
    https://www.simple-talk.com/sysadmin/exchange/exchange-e-mail-addresses-and-the-outlook-address-cache/
    In case if you don't want the users to use the autocomplete cache when composing the new emails :
    In group policy we can use the  office templates to disable the below mentioned option.
    1.use autocomplete to suggest the names ---> this option will comes under the advanced settings on the outlook client.
    In case if you don't want the users to use the autocomplete cache when composing the new emails as well as if you wanted to delete that autocomplete then you need to choose one more option along with the first one.
    1.Empty autocomplete cache.
    Please reply me if anyhitng is unclear.
    Thanks & Regards S.Nithyanandham

Maybe you are looking for