![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e763. Displaying the Menu in a JComboBox Component Using a Keystroke If the Selected Item Is Not UniqueThis 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(); } } } }
e757. Getting and Setting the Selected Item in a JComboBox Component e758. Getting the Items in a JComboBox Component e759. Adding and Removing an Item in a JComboBox Component e760. Selecting an Item in a JComboBox Component with Multiple Keystrokes e761. Determining If the Menu of a JComboBox Component Is Visible e762. Displaying the Menu in a JComboBox Component Using a Keystroke e764. Setting the Number of Visible Items in the Menu of a JComboBox Component e765. Listening for Changes to the Selected Item in a JComboBox Component e766. Listening for Action Events from a JComboBox Component e767. Determining When the Menu of a JComboBox Component Is Displayed © 2002 Addison-Wesley. |