栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用下拉列表在Java中创建自动填充文本框

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用下拉列表在Java中创建自动填充文本框

我使用了另一种方法:

它使用一个称为的自定义类,该类

AutoSuggestor
接受
a JTextField
,其单词
Windowan ArrayList<String>
来检查输入的单词,背景颜色和文本颜色以及建议焦点颜色以及不透明度值。通过传递
JTextField
引用
documentListener
,将添加a,它将执行以下操作:检查键入的单词以及是否显示建议以及是否显示建议。当一个单词键入的
documentListener
意志火
wordTyped(String wordTyped)
法与当前字所键入或(至少多少字有史以来已经输入),在
wordTyped(..)
这个词将被检查对那些在AutoSuggestor小号类 字典这是一个基本
ArrayList
String
这罐如下面的示例所示,可以即时设置:

在此处输入图片说明

(现在你将不得不使用鼠标单击要进行自动补全的词,或使用DOWN横向建议,该文本框,并ENTER使用遍历时选择的建议下键我还没有实现。UP还):

import java.awt.Color;import java.awt.Dimension;import java.awt.GridLayout;import java.awt.Window;import java.awt.event.ActionEvent;import java.awt.event.KeyEvent;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.util.ArrayList;import javax.swing.AbstractAction;import javax.swing.JComponent;import javax.swing.Jframe;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.JWindow;import javax.swing.KeyStroke;import javax.swing.SwingUtilities;import javax.swing.border.LineBorder;import javax.swing.event.documentEvent;import javax.swing.event.documentListener;public class Test {    public Test() {        Jframe frame = new Jframe();        frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);        JTextField f = new JTextField(10);        AutoSuggestor autoSuggestor = new AutoSuggestor(f, frame, null, Color.WHITE.brighter(), Color.BLUE, Color.RED, 0.75f) { @Override boolean wordTyped(String typedWord) {     //create list for dictionary this in your case might be done via calling a method which queries db and returns results as arraylist     ArrayList<String> words = new ArrayList<>();     words.add("hello");     words.add("heritage");     words.add("happiness");     words.add("goodbye");     words.add("cruel");     words.add("car");     words.add("war");     words.add("will");     words.add("world");     words.add("wall");     setDictionary(words);     //addToDictionary("bye");//adds a single word     return super.wordTyped(typedWord);//now call super to check for any matches against newest dictionary }        };        JPanel p = new JPanel();        p.add(f);        frame.add(p);        frame.pack();        frame.setVisible(true);    }    public static void main(String[] args) {        SwingUtilities.invokeLater(new Runnable() { @Override public void run() {     new Test(); }        });    }}class AutoSuggestor {    private final JTextField textField;    private final Window container;    private JPanel suggestionsPanel;    private JWindow autoSuggestionPopUpWindow;    private String typedWord;    private final ArrayList<String> dictionary = new ArrayList<>();    private int currentIndexOfSpace, tW, tH;    private documentListener documentListener = new documentListener() {        @Override        public void insertUpdate(documentEvent de) { checkForAndShowSuggestions();        }        @Override        public void removeUpdate(documentEvent de) { checkForAndShowSuggestions();        }        @Override        public void changedUpdate(documentEvent de) { checkForAndShowSuggestions();        }    };    private final Color suggestionsTextColor;    private final Color suggestionFocusedColor;    public AutoSuggestor(JTextField textField, Window mainWindow, ArrayList<String> words, Color popUpBackground, Color textColor, Color suggestionFocusedColor, float opacity) {        this.textField = textField;        this.suggestionsTextColor = textColor;        this.container = mainWindow;        this.suggestionFocusedColor = suggestionFocusedColor;        this.textField.getdocument().adddocumentListener(documentListener);        setDictionary(words);        typedWord = "";        currentIndexOfSpace = 0;        tW = 0;        tH = 0;        autoSuggestionPopUpWindow = new JWindow(mainWindow);        autoSuggestionPopUpWindow.setOpacity(opacity);        suggestionsPanel = new JPanel();        suggestionsPanel.setLayout(new GridLayout(0, 1));        suggestionsPanel.setBackground(popUpBackground);        addKeyBindingToRequestFocusInPopUpWindow();    }    private void addKeyBindingToRequestFocusInPopUpWindow() {        textField.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");        textField.getActionMap().put("Down released", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) {//focuses the first label on popwindow     for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {         if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {  ((SuggestionLabel) suggestionsPanel.getComponent(i)).setFocused(true);  autoSuggestionPopUpWindow.toFront();  autoSuggestionPopUpWindow.requestFocusInWindow();  suggestionsPanel.requestFocusInWindow();  suggestionsPanel.getComponent(i).requestFocusInWindow();  break;         }     } }        });        suggestionsPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");        suggestionsPanel.getActionMap().put("Down released", new AbstractAction() { int lastFocusableIndex = 0; @Override public void actionPerformed(ActionEvent ae) {//allows scrolling of labels in pop window (I know very hacky for now :))     ArrayList<SuggestionLabel> sls = getAddedSuggestionLabels();     int max = sls.size();     if (max > 1) {//more than 1 suggestion         for (int i = 0; i < max; i++) {  SuggestionLabel sl = sls.get(i);  if (sl.isFocused()) {      if (lastFocusableIndex == max - 1) {          lastFocusableIndex = 0;          sl.setFocused(false);          autoSuggestionPopUpWindow.setVisible(false);          setFocusToTextField();          checkForAndShowSuggestions();//fire method as if document listener change occured and fired it      } else {          sl.setFocused(false);          lastFocusableIndex = i;      }  } else if (lastFocusableIndex <= i) {      if (i < max) {          sl.setFocused(true);          autoSuggestionPopUpWindow.toFront();          autoSuggestionPopUpWindow.requestFocusInWindow();          suggestionsPanel.requestFocusInWindow();          suggestionsPanel.getComponent(i).requestFocusInWindow();          lastFocusableIndex = i;          break;      }  }         }     } else {//only a single suggestion was given         autoSuggestionPopUpWindow.setVisible(false);         setFocusToTextField();         checkForAndShowSuggestions();//fire method as if document listener change occured and fired it     } }        });    }    private void setFocusToTextField() {        container.toFront();        container.requestFocusInWindow();        textField.requestFocusInWindow();    }    public ArrayList<SuggestionLabel> getAddedSuggestionLabels() {        ArrayList<SuggestionLabel> sls = new ArrayList<>();        for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) { if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {     SuggestionLabel sl = (SuggestionLabel) suggestionsPanel.getComponent(i);     sls.add(sl); }        }        return sls;    }    private void checkForAndShowSuggestions() {        typedWord = getCurrentlyTypedWord();        suggestionsPanel.removeAll();//remove previos words/jlabels that were added        //used to calcualte size of JWindow as new Jlabels are added        tW = 0;        tH = 0;        boolean added = wordTyped(typedWord);        if (!added) { if (autoSuggestionPopUpWindow.isVisible()) {     autoSuggestionPopUpWindow.setVisible(false); }        } else { showPopUpWindow(); setFocusToTextField();        }    }    protected void addWordToSuggestions(String word) {        SuggestionLabel suggestionLabel = new SuggestionLabel(word, suggestionFocusedColor, suggestionsTextColor, this);        calculatePopUpWindowSize(suggestionLabel);        suggestionsPanel.add(suggestionLabel);    }    public String getCurrentlyTypedWord() {//get newest word after last white spaceif any or the first word if no white spaces        String text = textField.getText();        String wordBeingTyped = "";        if (text.contains(" ")) { int tmp = text.lastIndexOf(" "); if (tmp >= currentIndexOfSpace) {     currentIndexOfSpace = tmp;     wordBeingTyped = text.substring(text.lastIndexOf(" ")); }        } else { wordBeingTyped = text;        }        return wordBeingTyped.trim();    }    private void calculatePopUpWindowSize(JLabel label) {        //so we can size the JWindow correctly        if (tW < label.getPreferredSize().width) { tW = label.getPreferredSize().width;        }        tH += label.getPreferredSize().height;    }    private void showPopUpWindow() {        autoSuggestionPopUpWindow.getContentPane().add(suggestionsPanel);        autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textField.getWidth(), 30));        autoSuggestionPopUpWindow.setSize(tW, tH);        autoSuggestionPopUpWindow.setVisible(true);        int windowX = 0;        int windowY = 0;        windowX = container.getX() + textField.getX() + 5;        if (suggestionsPanel.getHeight() > autoSuggestionPopUpWindow.getMinimumSize().height) { windowY = container.getY() + textField.getY() + textField.getHeight() + autoSuggestionPopUpWindow.getMinimumSize().height;        } else { windowY = container.getY() + textField.getY() + textField.getHeight() + autoSuggestionPopUpWindow.getHeight();        }        autoSuggestionPopUpWindow.setLocation(windowX, windowY);        autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textField.getWidth(), 30));        autoSuggestionPopUpWindow.revalidate();        autoSuggestionPopUpWindow.repaint();    }    public void setDictionary(ArrayList<String> words) {        dictionary.clear();        if (words == null) { return;//so we can call constructor with null value for dictionary without exception thrown        }        for (String word : words) { dictionary.add(word);        }    }    public JWindow getAutoSuggestionPopUpWindow() {        return autoSuggestionPopUpWindow;    }    public Window getContainer() {        return container;    }    public JTextField getTextField() {        return textField;    }    public void addToDictionary(String word) {        dictionary.add(word);    }    boolean wordTyped(String typedWord) {        if (typedWord.isEmpty()) { return false;        }        //System.out.println("Typed word: " + typedWord);        boolean suggestionAdded = false;        for (String word : dictionary) {//get words in the dictionary which we added boolean fullymatches = true; for (int i = 0; i < typedWord.length(); i++) {//each string in the word     if (!typedWord.toLowerCase().startsWith(String.valueOf(word.toLowerCase().charAt(i)), i)) {//check for match         fullymatches = false;         break;     } } if (fullymatches) {     addWordToSuggestions(word);     suggestionAdded = true; }        }        return suggestionAdded;    }}class SuggestionLabel extends JLabel {    private boolean focused = false;    private final JWindow autoSuggestionsPopUpWindow;    private final JTextField textField;    private final AutoSuggestor autoSuggestor;    private Color suggestionsTextColor, suggestionBorderColor;    public SuggestionLabel(String string, final Color borderColor, Color suggestionsTextColor, AutoSuggestor autoSuggestor) {        super(string);        this.suggestionsTextColor = suggestionsTextColor;        this.autoSuggestor = autoSuggestor;        this.textField = autoSuggestor.getTextField();        this.suggestionBorderColor = borderColor;        this.autoSuggestionsPopUpWindow = autoSuggestor.getAutoSuggestionPopUpWindow();        initComponent();    }    private void initComponent() {        setFocusable(true);        setForeground(suggestionsTextColor);        addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) {     super.mouseClicked(me);     replaceWithSuggestedText();     autoSuggestionsPopUpWindow.setVisible(false); }        });        getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "Enter released");        getActionMap().put("Enter released", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) {     replaceWithSuggestedText();     autoSuggestionsPopUpWindow.setVisible(false); }        });    }    public void setFocused(boolean focused) {        if (focused) { setBorder(new LineBorder(suggestionBorderColor));        } else { setBorder(null);        }        repaint();        this.focused = focused;    }    public boolean isFocused() {        return focused;    }    private void replaceWithSuggestedText() {        String suggestedWord = getText();        String text = textField.getText();        String typedWord = autoSuggestor.getCurrentlyTypedWord();        String t = text.substring(0, text.lastIndexOf(typedWord));        String tmp = t + text.substring(text.lastIndexOf(typedWord)).replace(typedWord, suggestedWord);        textField.setText(tmp + " ");    }}

就目前而言,IMO唯一可能需要添加的内容是:

  • UP
    弹出自动提示框中的项目的关键焦点可遍历性,因此我们可以向上移动。
    如果有任何纠结,我会知道我能做什么。但是似乎运行良好。


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/456614.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号