如何在 JAVA GUI 中创建类似于 Google 搜索样式的搜索栏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26550559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:07:38  来源:igfitidea点击:

How to create a search bar similar to Google search style in JAVA GUI

javaswingsearchuser-interfacesearchbar

提问by Paul Ang

I am trying to create a search feature in my program similar to google search bar, where when user is typing it actually searches the database and displays the current result in a pop-out list below the JTextField. I am new to java GUI programming therefore I am unclear about all the java components therefore it is hard to find suitable components which fulfil my needs, especially the component I need to use for the pop out drop down list below the text field. I hope some experts can show me some insight.

我正在尝试在我的程序中创建一个类似于 google 搜索栏的搜索功能,当用户输入时,它实际上会搜索数据库并在JTextField. 我是 Java GUI 编程的新手,因此我不清楚所有的 Java 组件,因此很难找到满足我需求的合适组件,尤其是我需要用于文本字段下方弹出下拉列表的组件。我希望一些专家可以给我一些见解。

回答by Vighanesh Gursale

SwingX API would helpful to solve this issue. You can use the following code to implement auto complete feature to editable ComboBox.

SwingX API 将有助于解决这个问题。您可以使用以下代码为可编辑的 ComboBox 实现自动完成功能。

import javax.swing.*;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import java.awt.*;
public class Demo {

    JFrame frame = new JFrame("");
    AutoCompleteDecorator decorator;
    JComboBox combobox;

    public Demo() {
        combobox = new JComboBox(new Object[]{"","Ester", "Jordi",
            "Jordina", "Jorge", "Sergi"});
        AutoCompleteDecorator.decorate(combobox);
        frame.setSize(400,400);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());

        frame.add(combobox);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        Demo d = new Demo();
    }
}