Auto-Completion with JTextfield and JList
Problem Statement:
Develop a Java program that provides real-time suggestions when typing characters into a JTextfield, using a JList as the suggestion list.
Solution:
1. Prerequisites:
2. Implementation:
Create instances of Java2sAutoTextField and Java2sAutoComboBox. Populate the suggestion lists with initial values.
Set the font, colors, and initial text for the text field and combo box.
Add both components to a JFrame with a GridLayout. Set the default close operation, location, and pack the frame for display.
Code Example:
import java.awt.*; import java.util.ArrayList; import javax.swing.*; public class AutoCompleteTextField { // ... public AutoCompleteTextField() { // ... someTextField.setFont(new Font("Serif", Font.BOLD, 16)); someTextField.setForeground(Color.black); someTextField.setBackground(Color.orange); someTextField.setName("someTextField"); someTextField.setDataList(listSomeString); someComboBox.setPrototypeDisplayValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); someComboBox.setFont(new Font("Serif", Font.BOLD, 16)); someComboBox.setForeground(Color.black); someComboBox.setBackground(Color.YELLOW); ((JTextField) someComboBox.getEditor().getEditorComponent()).setDisabledTextColor(Color.black); someComboBox.setName("someComboBox"); someComboBox.setDataList(listSomeAnotherString); // ... } // ... }
Output:
Note:
This solution provides a basic auto-completion functionality. The suggestion list is static and can be customized to include dynamic data.
The above is the detailed content of How to Implement Real-Time Auto-Completion with JTextfield and JList in Java?. For more information, please follow other related articles on the PHP Chinese website!