java – 自动完成JTextField和箭头键

前端之家收集整理的这篇文章主要介绍了java – 自动完成JTextField和箭头键前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用 javax.swing.JList构建一个javax.swing.JTextField,用于自动完成,如Google.

当写一个字时,Google会显示几场比赛

>当按▼时,我可以使用▲和▼选择一些比赛
>可以用◀和▶编辑我的输入.
>当我按Enter键搜索框中的内容.
>当按Esc键时,盒子将更改为原始输入.

我的意思是关于Bible,我想在我学习这个词时寻找一个特定的单词.我看到了Java2sAutoTextField,但是没有箭头键的这个特殊行为.

解决方法

这需要一个自定义编码组件.绝对是一个扩展JTextField的类,并且在该类中有一个包含JList的JPopupMenu.您必须将JPopupMenu定位在文本字段的正下方,使其看起来像1个组件.

你的下一个诀窍就是在输入时进行过滤.我通常使用Java6 TableRowSorter与我预先填写数据的JTable结合使用.您将需要在JTextField上进行一些变更监听器,并拦截每个键入并获取数据.

>按键
>在DB中执行查询(或者某些数据存储获取类似的条目)
>用这些内容填充JTable
>使用基于JTextField条目的正则表达式设置RowFilter,以过滤检索到的数据
>使用关键听众管理您的操作

编辑

我鞭打了一个样品摇摆应用程序来显示我所说的话.这是一个复制/粘贴示例,应该正常工作(需要JDK 1.6).我基本上得到了你想要的,我把评论放在我告诉你填写空白的地方..例如,Escape键事件被消耗掉,你可以随便做任何事情.

initTableModel()方法只是使用数据初始化表模型.通常,您将要使用数据库或其他数据的动态填充表模型.很多可以调整,但这是例外的缘故;)所以这应该是一个很好的例子,让您修改完成您的目标.不止这个,你必须支付我$$$:)

package test.text.googleclone;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.regex.PatternSyntaxException;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

public class SearchAutoFillTest {

private JFrame frame = null;
private JTextField searchField = null;
private JPopupMenu popup = null;

private JTable searchTable = null;
private TableRowSorter<DefaultTableModel> rowSorter = null;
private DefaultTableModel searchTableModel = null;

public SearchAutoFillTest() {
    searchTableModel = new DefaultTableModel();
    initTableModel();

    rowSorter = new TableRowSorter<DefaultTableModel>(searchTableModel);
    searchTable = new JTable(searchTableModel);
    searchTable.setRowSorter(rowSorter);
    searchTable.setFillsViewportHeight(true);
    searchTable.getColumnModel().setColumnSelectionAllowed(false);
    searchTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    searchTable.getTableHeader().setReorderingAllowed(false);
    searchTable.setPreferredSize(new Dimension(775,100));
    searchTable.setGridColor(Color.WHITE);

    searchField = new JTextField();
    searchField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void changedUpdate(DocumentEvent e) {
            showPopup(e);
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            showPopup(e);
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            showPopup(e);
        }
    });

    searchField.addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(KeyEvent e) {

        }

        @Override
        public void keyReleased(KeyEvent e) {
            int code = e.getKeyCode();
            switch(code)
            {
                case KeyEvent.VK_UP:
                {
                    cycleTableSelectionUp();
                    break;
                }

                case KeyEvent.VK_DOWN:
                {
                    cycleTableSelectionDown();
                    break;
                }

                case KeyEvent.VK_LEFT:
                {
                    //Do whatever you want here
                    break;
                }

                case KeyEvent.VK_RIGHT:
                {
                    //Do whatever you want here
                    break;
                }
            }
        }

        @Override
        public void keyPressed(KeyEvent e) {

        }
    });

    KeyStroke keyStroke = KeyStroke.getKeyStroke("ESCAPE");
    searchField.getInputMap().put(keyStroke,"ESCAPE");
    searchField.getActionMap().put("ESCAPE",new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //Do what you wish here with the escape key.
        }
    });

    popup = new JPopupMenu();
    popup.add(searchTable);
    popup.setVisible(false);
    popup.setBorder(BorderFactory.createEmptyBorder());

    JPanel searchPanel = new JPanel(new BorderLayout(5,5));
    searchPanel.setBorder(BorderFactory.createEmptyBorder(4,4,4));
    searchPanel.add(searchField,BorderLayout.CENTER);

    frame = new JFrame();
    frame.setLayout(new BorderLayout(5,5));
    frame.add(searchPanel,BorderLayout.NORTH);
    frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800,500);
    center(frame);
    frame.setVisible(true);
}

private final void newFilter() {
    RowFilter<DefaultTableModel,Object> rf = null;

    try {
        rf = RowFilter.regexFilter(getFilterText(),0);
    }
    catch(PatternSyntaxException e) {
        return;
    }

    rowSorter.setRowFilter(rf);
}

private final String getFilterText() {
    String orig = searchField.getText();
    return "("+orig.toLowerCase()+")|("+orig.toUpperCase()+")";
}

private void showPopup(DocumentEvent e) {
    if(e.getDocument().getLength() > 0) {
        if(!popup.isVisible()) { 
            Rectangle r = searchField.getBounds();
            popup.show(searchField,(r.x-4),(r.y+16));
            popup.setVisible(true);
        }

        newFilter();
        searchField.grabFocus();

    }
    else {
        popup.setVisible(false);
    }
}

private void cycleTableSelectionUp() {
    ListSelectionModel selModel = searchTable.getSelectionModel();
    int index0 = selModel.getMinSelectionIndex();
    if(index0 > 0) {
        selModel.setSelectionInterval(index0-1,index0-1);
    }
}

private void cycleTableSelectionDown() {
    ListSelectionModel selModel = searchTable.getSelectionModel();
    int index0 = selModel.getMinSelectionIndex();
    if(index0 == -1) {
        selModel.setSelectionInterval(0,0);
    }
    else if(index0 > -1) {
        selModel.setSelectionInterval(index0+1,index0+1);
    }
}

private void initTableModel() {
    String[] columns = new String[] {"A"};
    String[][] data = new String[][]
    {
        new String[] {"a"},new String[] {"aa"},new String[] {"aaab"},new String[] {"aaabb"},new String[] {"aaabbbz"},new String[] {"b"},new String[] {"bb"},new String[] {"bbb"},new String[] {"bbbbbbb"},new String[] {"bbbbbbbeee"},new String[] {"bbbbbbbeeexxx"},new String[] {"ccc"},new String[] {"cccc"},new String[] {"ccccc"},new String[] {"cccccaaaa"},new String[] {"ccccccaaaa"},};

    searchTableModel.setDataVector(data,columns);
}

private void center(Window w) {
    int screenWidth  = Toolkit.getDefaultToolkit().getScreenSize().width;
    int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;

    int windowWidth = w.getWidth();
    int windowHeight = w.getHeight();

    if (windowHeight > screenHeight) {
        return;
    }

    if (windowWidth > screenWidth) {
        return;
    }

    int x = (screenWidth - windowWidth) / 2;
    int y = (screenHeight - windowHeight) / 2;

    w.setLocation(x,y);
}

public static void main(String ... args) {
    new SearchAutoFillTest();
}
}
原文链接:https://www.f2er.com/java/122786.html

猜你在找的Java相关文章