简体   繁体   English

将焦点设置为JList并在textField上移动光标以实现Java自动完成

[英]set focus to JList and have cursor on textField swing java autocomplete

I started to develop my own auto complete swing component and I want to set focus to the list when user press up or down keys and in the same time let the cursor on the textfield to allow him to type text or number.... 我开始开发自己的自动完成挥杆组件,并且希望在用户按下向上或向下键时将焦点设置到列表上,同时让文本字段上的光标允许他键入文本或数字。

to set focus to JList when typing up or down I have used 在我使用向上或向下键入时将焦点设置为JList

list.requestFocus(); list.requestFocus();

is there any way to have focus on JList and cursor on JTextField 有什么办法可以专注于JList和JTextField上的光标

please view the image in here 请在这里查看图片

here my code : 这是我的代码:

    package examples.autocomplete;

import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;

import com.gestioncaisse.dao.ClientDAO;
import com.gestioncaisse.dao.DAO;
import com.gestioncaisse.dao.MyConnection;
import com.gestioncaisse.pojos.Client;
import com.gestioncaisse.utils.utils;

public class testcombo extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    private JTextField textField;
    final DAO<Client> clientDao;
    List<Client> list_clients;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    testcombo frame = new testcombo();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    boolean first_time = true;

    /**
     * Create the frame.
     */
    public testcombo() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        clientDao = new ClientDAO(MyConnection.getInstance());

        list_clients = clientDao.findAll();

        textField = new JTextField();
        textField.setBounds(5, 11, 113, 20);

        textField.setColumns(10);

        final JButton btnNewButton = new JButton("...");
        btnNewButton.setBounds(116, 10, 45, 23);
        contentPane.setLayout(null);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(5, 31, 156, 144);

        final JList list = new JList(
                utils.fromListToObjectTable2Clients(list_clients));
        scrollPane.setViewportView(list);
        list.setVisibleRowCount(5);

        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        contentPane.add(scrollPane);
        contentPane.add(textField);
        contentPane.add(btnNewButton);

        textField.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent arg0) {
            }
            @Override
            public void keyReleased(KeyEvent arg0) {
                int a = list.getSelectedIndex();
                if (arg0.getKeyCode() == KeyEvent.VK_UP) {
                    list.requestFocus();
                } else if (arg0.getKeyCode() == KeyEvent.VK_DOWN) {
                    list.requestFocus();
                } else if (!first_time) {
                } else {
                    first_time = false;
                }
            }
            @Override
            public void keyPressed(KeyEvent arg0) {

            }
        });

    }
}

//if (a > 0)
//list.setSelectedIndex(a - 1);
//int first_vis = list.getFirstVisibleIndex();
//list.setListData(utils.fromListToObjectTable2Clients(clientDao.findByString(textField.getText())));
//list.setSelectedIndex(0);

Leave the focus on the JTextField but add KeyBindings to the UP/DOWN key. 将焦点放在JTextField上,但将UP或DOWN键添加KeyBindings In the actions just change selection in JList ( public void setSelectedIndex(int index) method) 在动作中,只需更改JList选择( public void setSelectedIndex(int index)方法)

UPDATE UPDATE

An aslternative way would be to have focus on JList and add KeyListener translating typed chars to the JTextField. 另一种方法是将重点放在JList上,并将将类型化的char转换为Key的KeyListener添加到JTextField中。 To Show caret use 显示插入符号使用

jTextFieldInstance.getCaret().setVisible(true);
jTextFieldInstance.getCaret().setSelectionVisible(true);

Here i used to retrieve matched data from database 在这里我曾经从数据库中检索匹配的数据

   keywordssearcher.setEditable(true);
    final JTextComponent sfield = (JTextComponent)    keywordssearcher.getEditor().getEditorComponent();
    sfield.setVisible(true);
    sfield.addKeyListener(new KeyAdapter() {

        @Override
        public void keyReleased(KeyEvent ke) {
            SwingUtilities.invokeLater(new Runnable() {

                public void run() {
                    comboFilter(sfield.getText(), con);
                }
            });
        }

        @Override
        public void keyPressed(KeyEvent e) {
            if (!(sfield.getText().equals("")) || (sfield.getText() == null)) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    addKeyWord(sfield.getText().toString());
                }
            }
        }
    });

  public void comboFilter(String enteredText, Connection ncon) {
    log.info("ncon autosuggest--->" + ncon);
    ArrayList<String> filterArray = new ArrayList<String>();
    String str1 = "";
    try {
        Statement stmt = dc.ConnectDB().createStatement();
        String str = "SELECT k_word FROM T_KeyWords WHERE k_word LIKE '" + enteredText + "%'";
        ResultSet rs = stmt.executeQuery(str);
        while (rs.next()) {
            str1 = rs.getString("k_word");
            filterArray.add(str1);
            con.close();
        }
    } catch (Exception ex) {
        log.error("Error in getting keywords from database" + ex.toString());
        JOptionPane.showMessageDialog(null, "Error in getting keywords from database" + ex.toString());
    }

    if (filterArray.size() > 0) {
        keywordssearcher.setModel(new DefaultComboBoxModel(filterArray.toArray()));
        keywordssearcher.setSelectedItem(enteredText);
        keywordssearcher.showPopup();
    } else {
        keywordssearcher.hidePopup();
    }
}

Here my keywordssearcher(jcombobox) is editable and the entered value can be added directly into the database. 在这里,我的keywordsearcher(jcombobox)是可编辑的,输入的值可以直接添加到数据库中。

use this as a reference and modify the code 以此为参考并修改代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM