e762. displaying the menu in a jcombobox component using a keystroke.txt

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

TXT
25
字号
By default, typing a key in a read-only combobox selects an item that starts with the typed key. This example demonstrates how to display the drop-down menu when a key is typed. 
    // Create a read-only combobox
    String[] items = {"Ant", "Ape", "Bat", "Boa", "Cat", "Cow"};
    JComboBox cb = new JComboBox(items);
    
    // Create and register the key listener
    cb.addKeyListener(new MyKeyListener());
    
    // This key listener displays the menu when a key is pressed.
    // To display the menu only if the pressed key matches or does not match an item,
    // see e763 Displaying the Menu in a JComboBox Component Using a Keystroke If the Selected Item Is Not Unique.
    class MyKeyListener extends KeyAdapter {
        public void keyPressed(KeyEvent evt) {
            JComboBox cb = (JComboBox)evt.getSource();
    
            // Get pressed character
            char ch = evt.getKeyChar();
    
            // If not a printable character, return
            if (ch != KeyEvent.CHAR_UNDEFINED) {
                cb.showPopup();
            }
        }
    }

⌨️ 快捷键说明

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