Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- import javax.swing.DefaultComboBoxModel;
- import javax.swing.JComboBox;
- import javax.swing.JFrame;
- import javax.swing.JTextField;
- import javax.swing.UIManager;
- import javax.swing.event.DocumentEvent;
- import javax.swing.event.DocumentListener;
- public class FilterComboBox extends JComboBox {
- private List<String> array;
- JTextField textfield;
- public FilterComboBox(List<String> array) {
- super(array.toArray());
- this.array = array;
- this.setEditable(true);
- textfield = (JTextField) this.getEditor().getEditorComponent();
- // textfield.addKeyListener(new KeyAdapter() {
- // public void keyReleased(KeyEvent ke) {
- // SwingUtilities.invokeLater(new Runnable() {
- // public void run() {
- // comboFilter(textfield.getText());
- // }
- // });
- // }
- // });
- textfield.getDocument().addDocumentListener(new DocumentListener() {
- @Override
- public void removeUpdate(DocumentEvent e) {
- callFIlter();
- }
- @Override
- public void insertUpdate(DocumentEvent e) {
- callFIlter();
- }
- @Override
- public void changedUpdate(DocumentEvent e) {
- }
- });
- }
- public void callFIlter() {
- try {
- String text = textfield.getDocument().getText(0, textfield.getDocument().getLength());
- comboFilter(text);
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- public synchronized void comboFilter(String enteredText) {
- List<String> autoCompleteArray = new ArrayList<String>();
- for (int i = 0; i < array.size(); i++) {
- if (array.get(i).toLowerCase().contains(enteredText.toLowerCase())) {
- autoCompleteArray.add(array.get(i));
- }
- }
- if (autoCompleteArray.size() > 0) {
- this.setModel(new DefaultComboBoxModel(autoCompleteArray.toArray()));
- this.setSelectedItem(enteredText);
- this.showPopup();
- } else {
- this.hidePopup();
- }
- }
- /* Testing Codes */
- public static List<String> populateArray() {
- List<String> test = new ArrayList<String>();
- test.add("");
- test.add("Mountain Flight");
- test.add("Mount Climbing");
- test.add("Trekking");
- test.add("Rafting");
- test.add("Jungle Safari");
- test.add("Bungie Jumping");
- test.add("Para Gliding");
- return test;
- }
- public static void makeUI() {
- JFrame frame = new JFrame("Adventure in Nepal - Combo Test");
- frame.getContentPane().add(new FilterComboBox(populateArray()));
- frame.pack();
- frame.setLocationByPlatform(true);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setVisible(true);
- }
- public static void main(String[] args) throws Exception {
- UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
- makeUI();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement