e763. displaying the menu in a jcombobox component using a keystroke if the selected item is not unique.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 38 行

TXT
38 行
字号
This example registers a key listener in a read-only combobox that displays the menu if the newly selected item is not unique. 
    // Create a read-only combobox
    String[] items = {"Ant", "Ape", "Bat", "Boa", "Cat"};
    JComboBox cb = new JComboBox(items);
    
    // Create and register the key listener
    cb.addKeyListener(new MyKeyListener());
    
    // This key listener displays the menu only if the pressed key
    // does not select a new item or if the selected item is not unique.
    class MyKeyListener extends KeyAdapter {
        public void keyPressed(KeyEvent evt) {
            JComboBox cb = (JComboBox)evt.getSource();
    
            // At this point, the selection in the combobox has already been
            // changed; get the index of the new selection
            int curIx = cb.getSelectedIndex();
    
            // Get pressed character
            char ch = evt.getKeyChar();
    
            // Get installed key selection manager
            JComboBox.KeySelectionManager ksm = cb.getKeySelectionManager();
            if (ksm != null) {
                // Determine if another item has the same prefix
                int ix = ksm.selectionForKey(ch, cb.getModel());
                boolean noMatch = ix < 0;
                boolean uniqueItem = ix == curIx;
    
                // Display menu if no matching items or the if the selection is not unique
                if (noMatch || !uniqueItem) {
                    cb.showPopup();
                }
            }
        }
    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?