0

I wrote small program for search Person's Name via Text field as I can search in mobile phone Contacts.

I put 5 names in combo box, when I search 'a' then it shows all 5 names because each have character 'a', then I select 3rd or 4th name by mouse, then it should show in Text field where I wrote 'a'.

Each time it replace 'a' in text field to 1st name in combo box, I want to write 2nd, 3rd character, or select from drop down list in combo box.

But I can't do that.

For reference here is my program

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

class SearchName extends JFrame {

    private static final long serialVersionUID = -3725136550174445695L;
    private final JPanel contentPane;
    private JTextField textField;
    private static JComboBox<Object> comboBox;
    private static final List<String> name_list = Arrays.asList("RAM", "Abraham", "Adam", "Dawson", "Elisha");
    private final Object[] nameArray = name_list.toArray();
    private static final String specailcharacter = "[^a-zA-Z0-9]";

    public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
        try {
            SearchName frame = new SearchName();
            frame.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        }
    });
    }

    public SearchName() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
    textField = new JTextField();
    textField.setBounds(10, 26, 297, 20);
    contentPane.add(textField);
    textField.setColumns(10);
    JButton btnNewButton = new JButton("Search");
    btnNewButton.setBounds(317, 25, 89, 23);
    contentPane.add(btnNewButton);
    comboBox = new JComboBox<Object>();
    comboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
        myBox(evt);
        }
    });
    comboBox.setVisible(true);
    comboBox.setOpaque(false);
    comboBox.setBorder(new LineBorder(new Color(171, 173, 179)));
    comboBox.setMaximumRowCount(20);
    comboBox.setBackground(Color.WHITE);
    comboBox.setBounds(10, 46, 297, 20);
    contentPane.add(comboBox);
    textField.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent arg0) {
        if (arg0 != null) {
            if (arg0.getSource() != null) {
            txtPassKeyTyped(arg0);
            }
        }
        }
    });
    }

    protected void myBox(ActionEvent evt) {
    if (comboBox.getSelectedItem() != null) {
        textField.setText(comboBox.getSelectedItem().toString());
    }
    }

    private void txtPassKeyTyped(KeyEvent arg0) {
    if (arg0 != null) {
        if (arg0.getSource() != null) {
        clear();
        if (comboBox.getItemCount() == 0) {
            textField = (JTextField) arg0.getSource();
            if (textField != null) {
            if (textField.getText() != null) {
                if (!textField.getText().isEmpty()) {
                search(textField.getText(), "name", nameArray.length, nameArray);
                try {
                    comboBox.showPopup();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                comboBox.setMaximumRowCount(20);
                }
            }
            }
        }
        }
    }

    }

    private void clear() {
    if (comboBox.getItemCount() > 0) {
        comboBox.removeAllItems();
        comboBox.setMaximumRowCount(0);
        comboBox.hidePopup();
    }
    }

    private static void search(String searchString, String type, int numberOfContacts, Object[] contacts) {
    if (searchString != null) {
        if (!searchString.isEmpty()) {
        int found = 0;
        int[] results = new int[numberOfContacts];
        Checker c = null;
        if (type.equals("name")) {
            c = new Checker() {
            public boolean check1(Object p, String searchString) {
                boolean a = false;
                if (p.toString().toLowerCase().replaceAll(specailcharacter, "").contains(searchString)) {
                a = true;
                } else if (p.toString().toUpperCase().replaceAll(specailcharacter, "")
                    .contains(searchString)) {
                a = true;
                } else if (p.toString().replaceAll(specailcharacter, "").contains(searchString)) {
                a = true;
                } else {
                a = false;
                }
                return a;
            }
            };
        }
        for (int x = 0; x < numberOfContacts; x++) {
            if (c != null) {
            if (c.check1(contacts[x], searchString)) {
                results[found] = x;
                found++;
            }
            }
        }
        if (found > 0) {
            for (int x = 0; x < found; x++) {
            comboBox.addItem(contacts[results[x]]);
            comboBox.revalidate();
            comboBox.repaint();
            }
        }
        }
    }
    }

    private static interface Checker {
    public boolean check1(Object p, String searchString);
    }
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Mandar Khire
  • 49
  • 2
  • 10

1 Answers1

1

You have to somehow reset the text when typing is finished.
Store the search text in a variable initialText and when typing is finished and listeners are triggered, reset it to this initial value.

private void txtPassKeyTyped(KeyEvent arg0) {
    if (arg0 != null) {
      if (arg0.getSource() != null) {
        clear();
        if (comboBox.getItemCount() == 0) {
          textField = (JTextField) arg0.getSource();
          if (textField != null) {
            String initialText = textField.getText();
            if (textField.getText() != null) {
              if (!textField.getText().isEmpty()) {
                search(textField.getText(), "name", nameArray.length, nameArray);
                try {
                  comboBox.showPopup();
                } catch (Exception e1) {
                  e1.printStackTrace();
                }
                comboBox.setMaximumRowCount(20);
              }
            }
            textField.setText(initialText);
          }
        }
      }
    }
  }
Apostolos
  • 10,033
  • 5
  • 24
  • 39
  • I know that, but then how I can set Jcombobox selected item, if I select 2nd or 3rd item by mouse 1 click. For that I will search 'a' & then 'm'. – Mandar Khire Jun 13 '18 at 13:25
  • i don't know if this is possible. `comboboxchanged` event is triggered in both cases. when you type and combobox is repainted and also when you select an item. so you want in first case to not set the text to selected item and in the second case to actually set it. – Apostolos Jun 13 '18 at 13:33
  • check my updated answer. I think this is what you want. – Apostolos Jun 13 '18 at 13:40
  • @MandarKhire if this solves your problem, dont forget to accept the answer in order for the question to be considered closed. thank you! :) – Apostolos Jun 13 '18 at 14:18