How to create an AutoCompleteField in java such as username field using JTextArea
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class Autocomplete extends JPanel { private final JTextField tf; private final JComboBox combo = new JComboBox(); private final Vector<String> v = new Vector<String>(); public Autocomplete() { super(new BorderLayout()); combo.setEditable(true); tf = (JTextField) combo.getEditor().getEditorComponent(); tf.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { EventQueue.invokeLater(new Runnable() { public void run() { String text = tf.getText(); if (text.length() == 0) { combo.hidePopup(); setModel(new DefaultComboBoxModel(v), ""); } else { DefaultComboBoxModel m = getSuggestedModel(v, text); if (m.getSize() == 0 || hide_flag) { combo.hidePopup(); hide_flag = false; } else { setModel(m, text); combo.showPopup(); } } } }); } public void keyPressed(KeyEvent e) { String text = tf.getText(); int code = e.getKeyCode(); if (code == KeyEvent.VK_ENTER) { if (!v.contains(text)) { v.addElement(text); Collections.sort(v); setModel(getSuggestedModel(v, text), text); } hide_flag = true; } else if (code == KeyEvent.VK_ESCAPE) { hide_flag = true; } else if (code == KeyEvent.VK_RIGHT) { for (int i = 0; i < v.size(); i++) { String str = v.elementAt(i); if (str.startsWith(text)) { combo.setSelectedIndex(-1); tf.setText(str); return; } } } } });
continue..
String[] countries = { "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Argentina", "Armenia", "Austria", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Benin", "Bhutan", "Bolivia", "Bosnia & Herzegovina", "Botswana", "Brazil", "Bulgaria", "Burkina Faso", "Burma", "Burundi", "Cambodia", "Cameroon", "Canada", "China", "Colombia", "Comoros", "Congo", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Georgia", "Germany", "Ghana", "Great Britain", "Greece", "Hungary", "Holland", "India", "Iran", "Iraq", "Italy", "Somalia", "Spain", "Sri Lanka", "Sudan", "Suriname", "Swaziland", "Sweden", "Switzerland", "Syria", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Yemen", "Zaire", "Zambia", "Zimbabwe" }; for (int i = 0; i < countries.length; i++) { v.addElement(countries[i]); } setModel(new DefaultComboBoxModel(v), ""); JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createTitledBorder("Autosuggestion Box")); p.add(combo, BorderLayout.NORTH); add(p); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setPreferredSize(new Dimension(300, 150)); } private boolean hide_flag = false; private void setModel(DefaultComboBoxModel mdl, String str) { combo.setModel(mdl); combo.setSelectedIndex(-1); tf.setText(str); } private static DefaultComboBoxModel getSuggestedModel( java.util.List<String> list, String text) { DefaultComboBoxModel m = new DefaultComboBoxModel(); for (String s : list) { if (s.startsWith(text)) m.addElement(s); } return m; } public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new Autocomplete()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
Thanks for ur reply. Now i did in a diff way with the help of ur code. :-
package classes.AutoCompleteExample;
import java.awt.BorderLayout; import java.awt.event.KeyEvent; import java.awt.event.KeyListener;
import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JTextField;
/** * @author Ajmal Muhamad P * */
@SuppressWarnings("serial") public class AutoCompleteField extends JFrame implements KeyListener {
private JTextField textField; private JComboBox combo; private DataBaseManager dbMgr; private String Filter; private boolean dataChngd; public static void main(String[] args) { // TODO Auto-generated method stub new AutoCompleteField(); } public AutoCompleteField() { // TODO Auto-generated constructor stub super("Interface Test"); Filter = ""; dataChngd = false; setBounds(100, 100, 300, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); dbMgr = new DataBaseManager(); combo = new JComboBox(dbMgr.getCountry("")); combo.setSelectedIndex(-1); // 0 specifies the first item in the list and -1 indicates no selection combo.setEditable(true); combo.setMaximumRowCount(5); textField = (JTextField) combo.getEditor().getEditorComponent(); getContentPane().add(combo, BorderLayout.NORTH); textField.addKeyListener(this); setVisible(true); } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub String temp_Filter = textField.getText(); if(dataChngd == true && temp_Filter.equals(Filter) == false) Filter = temp_Filter; if(dataChngd == true) { combo.setModel(new DefaultComboBoxModel(dbMgr.getCountry(Filter))); combo.setSelectedIndex(-1); // 0 specifies the first item in the list and -1 indicates no selection textField.setText(Filter); } int item_Cnt = combo.getItemCount(); if(dataChngd == true) if(item_Cnt > 1 || (item_Cnt == 1 && !combo.getItemAt(0).equals(Filter))) combo.showPopup(); dataChngd = false; } @Override public void keyPressed(KeyEvent e) {} @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub if(e.getKeyChar() == KeyEvent.VK_ESCAPE) textField.setText(Filter); else dataChngd = true; }
}
package classes.InterfaceExample; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Vector; /** * @author Ajmal Muhammad P * */ public class DataBaseManager { public DataBaseManager() { // TODO Auto-generated constructor stub try { Class.forName("org.sqlite.JDBC"); } catch (ClassNotFoundException e1) {} } public Vector<String> getCountry(String filter) { // TODO Auto-generated method stub Vector<String> retVector = new Vector<String>(); try { Connection conn = DriverManager.getConnection("jdbc:sqlite:AutoCompleteField.db"); Statement stat = conn.createStatement(); ResultSet result = stat.executeQuery("SELECT country FROM ACF WHERE country LIKE '"+ filter +"%' ORDER BY country"); while (result.next()) retVector.add(result.getString(1)); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return retVector; } }
Ads