View Javadoc
1   package edu.jiangxin.apktoolbox.swing.extend.autocomplete;
2   
3   import javax.swing.*;
4   import java.io.Serial;
5   import java.util.Vector;
6   
7   /**
8    * @author jiangxin
9    * @author 2018-09-09
10   *
11   */
12  public class AutoCompleteComboBox<E> extends JComboBox<E> {
13  
14      @Serial
15      private static final long serialVersionUID = 1L;
16      private transient AutoCompleter<E> completer;
17  
18      public AutoCompleteComboBox() {
19          super();
20          setUI(new ScrollBasicComboBoxUI());
21          addCompleter();
22      }
23  
24      public AutoCompleteComboBox(ComboBoxModel<E> cm) {
25          super(cm);
26          addCompleter();
27      }
28  
29      public AutoCompleteComboBox(E[] items) {
30          super(items);
31          addCompleter();
32      }
33  
34      public AutoCompleteComboBox(Vector<E> v) {
35          super(v);
36          addCompleter();
37      }
38  
39      private void addCompleter() {
40          setEditable(true);
41          completer = new AutoCompleter<>(this);
42      }
43  
44      public void autoComplete(String str) {
45          this.completer.autoComplete(str);
46      }
47  
48      public String getText() {
49          return ((JTextField) getEditor().getEditorComponent()).getText();
50      }
51  
52      public void setText(String text) {
53          ((JTextField) getEditor().getEditorComponent()).setText(text);
54      }
55  
56      public boolean containsItem(String itemString) {
57          for (int i = 0; i < this.getModel().getSize(); i++) {
58              String item = " " + this.getModel().getElementAt(i);
59              if (item.equals(itemString)) {
60                  return true;
61              }
62          }
63          return false;
64      }
65  }
66