The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing  [141 examples] > JComboBox  [12 examples]

e762. Displaying the Menu in a JComboBox Component Using a Keystroke

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();
            }
        }
    }

 Related Examples
e756. Creating a JComboBox Component
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
e763. Displaying the Menu in a JComboBox Component Using a Keystroke If the Selected Item Is Not Unique
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

See also: Actions    JButton    JCheckBox    JDesktop and JInternalFrame    JFrame, JWindow, JDialog    JLabel    JList    JProgressBar    JRadioButton    JScrollPane    JSlider    JSpinner    JSplitPane    JTabbedPane    JToolBar    Keystrokes and Input Maps    Layout    Look and Feel    Menus    Progress Monitor    The Screen    Tool Tips    UI Default Values   


© 2002 Addison-Wesley.