JCombobox implements retrievable drop-down lists in java Swing

Keywords: Java Windows IE Programming

This is to be implemented by yourself. Here's a demo code for you.
You can modify it yourself.

/* 
Among many Windows applications, IE's address bar is the most common one. When we're in ComboBox's text box content, we can see that
Its drop-down list automatically lists the most matched items and displays the most matched items in the input box.

There is a JComboBox class in Java that can implement drop-down selection or input selection.  
But it does not provide automatic lookup and completion. Now let's "refit" this class to enable it to automatically find and complete.

The refitting ideas are as follows:

1. Inherit a JComboBox class and set Editable as true. In this way, users can enter text on combobox.

2. We know that the combobox input box is a JTextField, which can be obtained by comboBox.getEditor().getEditorComponent().

3. Add a KeyListener to the text box.

4. When the user keys in the text box, the key Released event will be released. In this event, we write the main code to realize automatic search and completion.

The idea is so simple, and the automatic search algorithm can be written by anyone who is familiar with programming. I list the complete program code as follows:
 

/*******************************************************************************
 * @project: JAutoCompleteComboBox
 * @package: test
 * @file: JAutoCompleteComboBox.java
 * @author: zhangpei
 * @created: 2019-4-18
 * @purpose:
 * 
 * @version: 1.0
 * 
 * Revision History at the end of file.
 * 
 * Copyright 2019 esoon-tech All rights reserved.
 ******************************************************************************/

/**   
 * @Title: JAutoCompleteComboBox.java 
 * @Package test 
 * @Description: TODO(Describe what the document does in one sentence. 
 * @author Burns[Zhang Pei   
 * @date 2019-4-18 11:45:57 a.m. 
 * @version V1.0   
 */
package test;

/** 
 * @ClassName: JAutoCompleteComboBox 
 * @Description: TODO(Here is a sentence describing the function of this class. 
 * @author Burns[Zhang Pei 
 * @date 2019-4-18 11:45:57 a.m. 
 *  
 */

import java.awt.event.ItemEvent;

import java.awt.event.ItemListener;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.util.List;

import java.util.Vector;

import javax.swing.ComboBoxModel;

import javax.swing.DefaultComboBoxModel;

import javax.swing.JComboBox;

import javax.swing.JFrame;

import javax.swing.JTextField;

public class JAutoCompleteComboBox extends JComboBox {

	private AutoCompleter completer;

	public JAutoCompleteComboBox() {
		super();
		addCompleter();
	}

	public JAutoCompleteComboBox(ComboBoxModel cm) {
		super(cm);
		addCompleter();
	}

	public JAutoCompleteComboBox(Object[] items) {
		super(items);
		addCompleter();
	}

	public JAutoCompleteComboBox(List v) {
		super((Vector) v);
		addCompleter();
	}

	private void addCompleter() {
		setEditable(true);
		completer = new AutoCompleter(this);
	}

	public void autoComplete(String str) {
		this.completer.autoComplete(str, str.length());
	}

	public String getText() {
		return ((JTextField) getEditor().getEditorComponent()).getText();
	}

	public void setText(String text) {
		((JTextField) getEditor().getEditorComponent()).setText(text);
	}

	public boolean containsItem(String itemString) {
		for (int i = 0; i < this.getModel().getSize(); i++) {
			String _item = " " + this.getModel().getElementAt(i);
			if (_item.equals(itemString))
				return true;
		}
		return false;
	}

	public static void main(String[] args) {
		JFrame frame = new JFrame();
		Object[] items = new Object[] { "", "abc ", "aab ", "aba ", "hpp ",
				"pp ", "hlp " };
		DefaultComboBoxModel model = new DefaultComboBoxModel();
		JComboBox cmb = new JAutoCompleteComboBox(model);
		model.addElement("");
		model.addElement("abc ");
		model.addElement("aab ");
		model.addElement("aba ");
		model.addElement("hpp ");
		model.addElement("pp ");
		model.addElement("hlp ");
		frame.getContentPane().add(cmb);
		frame.setSize(400, 80);
		frame.setVisible(true);
	}
}

/**
 * /****************************************************************************
 * *** <B>Revision History</B><BR>
 * [type 'revision' and press Alt + / to insert revision block]<BR>
 * 
 * 
 * 
 * Copyright 2019 esoon-tech All rights reserved.
 ******************************************************************************/

 

/*******************************************************************************
 * @project: JAutoCompleteComboBox
 * @package: test
 * @file: AutoCompleter.java
 * @author: zhangpei
 * @created: 2019-4-18
 * @purpose:
 * 
 * @version: 1.0
 * 
 * Revision History at the end of file.
 * 
 * Copyright 2019 esoon-tech All rights reserved.
 ******************************************************************************/

/**   
 * @Title: AutoCompleter.java 
 * @Package test 
 * @Description: TODO(Describe what the document does in one sentence. 
 * @author Burns[Zhang Pei   
 * @date 2019-4-18 11:47 a.m. 
 * @version V1.0   
 */
package test;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;
import java.util.Vector;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JTextField;

/** 
 * @ClassName: AutoCompleter 
 * @Description: TODO(Here is a sentence describing the function of this class. 
 * @author Burns[Zhang Pei 
 * @date 2019-4-18 11:47 a.m. 
 *  
 */
/**
 * Automatic Completor. Automatically find the most matching items and rank at the top of the list.
 * 
 * @author Turbo Chen
 */
class AutoCompleter implements KeyListener, ItemListener {

	private JComboBox owner = null;
	private JTextField editor = null;
	private ComboBoxModel model = null;

	public AutoCompleter(JComboBox comboBox) {
		owner = comboBox;
		editor = (JTextField) comboBox.getEditor().getEditorComponent();
		editor.addKeyListener(this);
		model = comboBox.getModel();

		owner.addItemListener(this);
	}

	public void keyTyped(KeyEvent e) {
	}

	public void keyPressed(KeyEvent e) {
	}

	public void keyReleased(KeyEvent e) {
		char ch = e.getKeyChar();
		if (ch == KeyEvent.CHAR_UNDEFINED || Character.isISOControl(ch)
				|| ch == KeyEvent.VK_DELETE)
			return;

		int caretPosition = editor.getCaretPosition();
		String str = editor.getText();
		if (str.length() == 0)
			return;
		autoComplete(str, caretPosition);
	}

	/**
	 * Automatic completion. Find similar items in the list based on the input.
	 */
	protected void autoComplete(String strf, int caretPosition) {
		Object[] opts;
		opts = getMatchingOptions(strf.substring(0, caretPosition));
		if (owner != null) {
			model = new DefaultComboBoxModel(opts);
			owner.setModel(model);
		}
		if (opts.length > 0) {
			String str = opts[0].toString();
			editor.setCaretPosition(caretPosition);
			if (owner != null) {
				try {
					owner.showPopup();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	/**
	 * 
	 * Find similar items and rank them at the top of the array.
	 * 
	 * @param str
	 * @return Returns a list of all items.
	 */
	protected Object[] getMatchingOptions(String str) {
		List v = new Vector();
		List v1 = new Vector();

		for (int k = 0; k < model.getSize(); k++) {
			Object itemObj = model.getElementAt(k);
			if (itemObj != null) {
				String item = itemObj.toString().toLowerCase();
				if (item.startsWith(str.toLowerCase()))
					v.add(model.getElementAt(k));
				else
					v1.add(model.getElementAt(k));
			} else
				v1.add(model.getElementAt(k));
		}
		for (int i = 0; i < v1.size(); i++) {
			v.add(v1.get(i));
		}
		if (v.isEmpty())
			v.add(str);
		return v.toArray();
	}

	public void itemStateChanged(ItemEvent event) {
		if (event.getStateChange() == ItemEvent.SELECTED) {
			int caretPosition = editor.getCaretPosition();
			if (caretPosition != -1) {
				try {
					editor.moveCaretPosition(caretPosition);
				} catch (IllegalArgumentException ex) {
					ex.printStackTrace();
				}
			}
		}
	}
}

/*******************************************************************************
 * <B>Revision History</B><BR>
 * [type 'revision' and press Alt + / to insert revision block]<BR>
 * 
 * 
 * 
 * Copyright 2019 esoon-tech All rights reserved.
 ******************************************************************************/

Wish you success!

 

Posted by israfel on Sat, 11 May 2019 02:27:09 -0700