Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners AutoCompleteField using JTextArea

Have Programming Question? Ask it here!
 
 
 


Ajmal Muhammad P
AutoCompleteField using JTextArea
4 Answer(s)      2 years and 11 months ago
Posted in : Java Beginners


How to create an AutoCompleteField in java such as username field using JTextArea


Advertisement
View Answers

August 19, 2011 at 5:36 PM


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;
                        }
                    }
                }
            }
        });


August 19, 2011 at 5:37 PM


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);
    }
}


August 22, 2011 at 12:40 PM


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;

}

}



August 22, 2011 at 3:29 PM


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;

    }

}


Related Tutorials/Questions & Answers:
AutoCompleteField using JTextArea
AutoCompleteField using JTextArea  How to create an AutoCompleteField in java such as username field using JTextArea
jtextarea
jtextarea  how to use append function in jtextarea?? i have build an application and i have to display only particular column data which can have multiple rows.it is not working with settext but using using append the value gets
Advertisements
jtextarea
jtextarea  how to use append function in jtextarea?? i have build an application and i have to display only particular column data which can have multiple rows.it is not working with settext but using using append the value gets
jtextarea
jtextarea   How To: Add line numbers to JTextArea?? help
jTextArea
jTextArea  how to get each/all values from ms access database into jtextarea of a particular entity..??Please Help
jTextArea
jTextArea  can jtextarea have numbers like 1 will be set to default and when the user writes in first line and hits enter the 2nd number should automatically be created??can this be done in netbeans??please help
JTextfields working with JTextArea
on a Jtextarea   hi friend, try the following code below : import java.sql.... = new JTextField(); JTextArea textarea=new JTextArea(5,20); JButton b=new
JTextArea - Swing AWT
JTextArea  Dear Sir, I was hoping you could please help me on, how to restrict the maximum characters that the user can Enter in the JTextArea of my Application. I want that the User can Enter only 300 Characters, not more
view data from jTextArea to jtable
view data from jTextArea to jtable  good night Please help senior java all, I want to make a brief program of reading data in the text area and then on the show to the j table. I created a new scrip like below but it does
How to get filename in JTextArea in following case?
How to get filename in JTextArea in following case?  Hi, i'm... is not displayed in the JTextArea, why? [CODE] private void... JFrame { JTextArea JTextAreaOutputDirectory; JButton b; JScrollPane
JTextArea
Java: JTextArea Description A javax.swing.JTextArea is a multi-line text... use JTextField. Constructors JTextArea ta = new JTextArea(int rows, int cols); JTextArea ta = new JTextArea(String initialText, int rows, int cols
How To Fetch Data From Database Into JTextArea
to the JTextArea by using the method setText() of JTextComponent. Before...How To Fetch Data From Database Into JTextArea In this section we will read about how to get the data from database table into JTextArea
how to send the content of jtextarea from netbeans IDE to webpage's textarea in java
how to send the content of jtextarea from netbeans IDE to webpage's textarea in java   Hi, i m interested to send the content of my jtextarea which i have developed in netbeans IDE to the webpage's textarea. how can i do
JTextArea
Java: Example - JTextArea   This is how the window looks... if there is sufficient data in the JTextArea to make them necessary.   In this example how to create object of JTextArea and add to the swing
Java JTextArea
Java JTextArea In this section we will discuss about the javax.swing.JTextArea. javax.swing.JTextArea extends the JTextComponent. JTextArea facilitates... is capable to be placed within the JScrollpane if JtextArea is required to add
JTextArea to Word Document
JTextArea to Word Document Jakarta POI has provided several classes... saved in the word file using POI classes. And you can view your file by clicking... org.apache.poi.hwpf.extractor.WordExtractor; public class TextAreaInDocument extends JFrame { JTextArea area
how to convert doc file into html using java swing
how to convert doc file into html using java swing  i want to convert doc file into html and display it on jtextarea please help me and give the sample code
Lost Using Swing Components
Lost Using Swing Components  Hello, I sound like every other newbie... here. private JButton sendButton = new JButton("Send"); private JTextArea message = new JTextArea(4, 22); public JEMail() { super("WebBuy Company E
Lost Using Swing Components
Lost Using Swing Components  Hello, I sound like every other newbie... here. private JButton sendButton = new JButton("Send"); private JTextArea message = new JTextArea(4, 22); public JEMail() { super("WebBuy Company E
Lost Using Swing Components
Lost Using Swing Components  Hello, I sound like every other newbie but I desperately need help. I have to write an application for the WebBuy..."); private JTextArea message = new JTextArea(4, 22); public JEMail
using array
using array  transpose a matrix
using array
using array  transpose a matrix
how to print fasta file into jtable using netbeans IDE
how to print fasta file into jtable using netbeans IDE   mt file is : contig00001 length=586 numreads=4.... and sequence "CGGGAAATTATCc..." in jtextarea. i made both jtable and jtextarea
Lost Using Swing Components(2)
Lost Using Swing Components(2)  Here is the code block corrected: //Insert missing code here. import java.awt.*; import java.awt.event.*; public... = new JButton("Send"); private JTextArea message = new JTextArea(4, 22
using array
using array  column wise total of a matrix
using prompt
using prompt  how to use prompt
using function
using function   using a function to find the value of v from the foiiowing expression 1v=1u+1*f
using array
using array  Circular left shift array element by one position
using array
using array  Circular left shift array element by one position
using array
using array  read 10 digit number and display (star
using array
using array  display 10 digit number using array and print pyramid. 1 1 1 1 1 1 1 1 1 1 1 1
Lost Using Swing Components(3)
Lost Using Swing Components(3)  Hello, I sound like every other newbie but I desperately need help. I have to write an application for the WebBuy... JTextArea message = new JTextArea(4, 22); public JEMail() { super
Simple Editor
a JTextArea with Actions to implement the menu items. Actions are a good way... JFrame { //-- Components private JTextArea mEditArea; private... JTextArea(15, 80); mEditArea.setBorder
Using Ajax
Using Ajax  Hi, How I can use Ajax in web programming? Tell me any example which using Ajax to call server side script? Thanks   Hi, Here are examples: PHP Ajax and Database First Ajax Example Getting Started
using for loop
using for loop  what will be the source code of the program that the output will be printing all numbers that is divisible by 3 and 5 sample output: 3 is divisible by 3 5 is divisible by 5 6 is divisible by 3 9 is divisible by 3
create , edit MS WORD like document file using Java Swing - Swing AWT
create , edit MS WORD like document file using Java Swing   In my program I have JTextArea. Text in JTextArea can be set to selected font, font style etc. I want this text in JTextArea to be saved to MS WORD like
using function
using function  write a program using function overloading to accept any sentence and print vowels and consonants sepratly   Here is an example that accepts a sentence from the user and display the vowels and consonants
using iReport
using iReport  Hello sir, I am using iReport3.0 and then i am calling the .jrxml file in jsp but i got the error.My JSP code is as below and after the jsp code i have placed the error code Thanks in advance: &lt
using constructor
using constructor  all constructor for matrix class?   The given code implements the Matrix class and show the addition of two matrices. public class Matrix{ int M; int N
using eval in Java
using eval in Java  using eval in Java
Using Unicode Variable Names - Java Tutorials
Using Unicode Variable Names 2001-11-23 The Java Specialists' Newsletter [Issue 036] - Using Unicode Variable Names Author: Dr. Heinz M. Kabutz... of the earth. As a result of using Dragon NaturallySpeaking, you
Is JSF using JSP?
Is JSF using JSP?  Is JSF using JSP
string palindrom using vbscript?
string palindrom using vbscript?  string palindrom using vbscript
write a programm using java
write a programm using java  print the following using java programming
Using throw in java method
Using throw in java method  using throw with method implies what
why using static keyword
why using static keyword  why using static keyword
Image Movement using Swings
Image Movement using Swings  How to move image using Swings
Date object using JavaScript
Date object using JavaScript  What's the Date object using JavaScript
delete an entry using JavaScript
delete an entry using JavaScript  How to delete an entry using JavaScript
Advertisements
 

 

 

DMCA.com