讓JTextField添加“自動完成”功能

來源:互聯網
上載者:User
package com.moya.test;import java.awt.BorderLayout;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.util.ArrayList;import java.util.Locale;import javax.swing.DefaultComboBoxModel;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JTextField;import javax.swing.UIManager;import javax.swing.event.DocumentEvent;import javax.swing.event.DocumentListener;public class TestAutoComplete {public static void main(String[] args) throws Exception {         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());         JFrame frame = new JFrame();         frame.setTitle("Auto Completion Test");         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         frame.setBounds(200, 200, 500, 400);         ArrayList<String> items = new ArrayList<String>();         Locale[] locales = Locale.getAvailableLocales();         for (int i = 0; i < locales.length; i++) {             String item = locales[i].getDisplayName();               items.add(item);         }         JTextField txtInput = new JTextField();                  setupAutoComplete(txtInput, items);         txtInput.setColumns(30);         frame.getContentPane().setLayout(new FlowLayout());         frame.getContentPane().add(txtInput, BorderLayout.NORTH);            frame.setVisible(true);     }private static boolean isAdjusting(JComboBox cbInput) {if (cbInput.getClientProperty("is_adjusting") instanceof Boolean) {return (Boolean) cbInput.getClientProperty("is_adjusting");}return false;}private static void setAdjusting(JComboBox cbInput, boolean adjusting) {cbInput.putClientProperty("is_adjusting", adjusting);}public static void setupAutoComplete(final JTextField txtInput, final ArrayList<String> items) {final DefaultComboBoxModel model = new DefaultComboBoxModel();final JComboBox cbInput = new JComboBox(model) {public Dimension getPreferredSize() {return new Dimension(super.getPreferredSize().width, 0);}};setAdjusting(cbInput, false);for (String item : items) {model.addElement(item);}cbInput.setSelectedItem(null);cbInput.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if (!isAdjusting(cbInput)) {if (cbInput.getSelectedItem() != null) {txtInput.setText(cbInput.getSelectedItem().toString());}}}});txtInput.addKeyListener(new KeyAdapter() {@Overridepublic void keyPressed(KeyEvent e) {setAdjusting(cbInput, true);if (e.getKeyCode() == KeyEvent.VK_SPACE) {if (cbInput.isPopupVisible()) {e.setKeyCode(KeyEvent.VK_ENTER);}}if (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN) {e.setSource(cbInput);cbInput.dispatchEvent(e);if (e.getKeyCode() == KeyEvent.VK_ENTER) {txtInput.setText(cbInput.getSelectedItem().toString());cbInput.setPopupVisible(false);}}if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {cbInput.setPopupVisible(false);}setAdjusting(cbInput, false);}});txtInput.getDocument().addDocumentListener(new DocumentListener() {public void insertUpdate(DocumentEvent e) {updateList();}public void removeUpdate(DocumentEvent e) {updateList();}public void changedUpdate(DocumentEvent e) {updateList();}private void updateList() {setAdjusting(cbInput, true);model.removeAllElements();String input = txtInput.getText();if (input!=null && !input.trim().equals("")) {for (String item : items) {if (item.toLowerCase().startsWith(input.toLowerCase())) {model.addElement(item);}}}cbInput.setPopupVisible(model.getSize() > 0);setAdjusting(cbInput, false);}});txtInput.setLayout(new BorderLayout());txtInput.add(cbInput, BorderLayout.SOUTH);}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.