简体   繁体   中英

How i handle keypress event for Jcombobox in java

I want to add item to JCombobox , that item is what I typed in JCombobox which is item to be add. this jCombox box is editable.

How can i do this.

Ok i tryied add KeyPress event for this JCombo box but it doesn't respose

 private void jbcBOXKeyTyped(java.awt.event.KeyEvent evt) {

        if (evt.getKeyCode() == 13) {
            System.out.println("Keypress");
            jbcBOX.addItem(jbcBOX.getSelectedItem().toString());
        }
    }

Made a short example hope it helps.

Basically just adds ActionListener to JComboBox the ActionListener is called whenever an item is selected or added. In the ActionListener we simply check if there is an item that matches the currently selected item, if not then add the item to JComboBox if a match is found then do nothing:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class EditableJComboBox {

    public EditableJComboBox() {
        initComponents();
    }

    private void initComponents() {
        JFrame frame = new JFrame("Editable JComboBox");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        String labels[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
        final JComboBox comboBox = new JComboBox(labels);
        comboBox.setEditable(true);

        comboBox.addActionListener(new ActionListener() {
            private boolean found = false;

            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                String s = (String) comboBox.getSelectedItem();
                for (int i = 0; i < comboBox.getItemCount(); i++) {
                    if (comboBox.getItemAt(i).toString().equals(s)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    System.out.println("Added: " + s);
                    comboBox.addItem(s);
                }
                found = false;
            }
        });

        frame.add(comboBox);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new EditableJComboBox();
            }
        });
    }
}

This is explained in the Combobox tutorial . No need for dirty KeyListener s and checks for the enter key.

  1. You make the combobox editable
  2. You add an ActionListener which will be triggered when the enter key is hit
  3. In your ActionListener you can update the model

Or to quote that tutorial more literally

JComboBox patternList = new JComboBox(patternExamples);
patternList.setEditable(true);
patternList.addActionListener(this);

An editable combo box fires an action event when the user chooses an item from the menu and when the user types Enter. Note that the menu remains unchanged when the user enters a value into the combo box. If you want, you can easily write an action listener that adds a new item to the combo box's menu each time the user types in a unique value.

It's worse than even this says - it seems (from using Netbeans) keyTyped etc events simply don't fire. I imagine a great number of people are here wondering why they can catch java.awt.event.KeyEvent.getKeyChar() on a JTextField but using exactly the coresponding part of the GUI Builder (in Netbeans) for a JComboBox gets them absolutely nothing!

Handling Events on a Combo Box

...

Although JComboBox inherits methods to register listeners for low-level events — focus, key, and mouse events, for example — we recommend that you don't listen for low-level events on a combo box . Here's why: A combo box is a compound component — it is comprised of two or more other components. The combo box itself fires high-level events such as action events. Its subcomponents fire low-level events such as mouse, key, and focus events. The low-level events and the subcomponent that fires them are look-and-feel-dependent. To avoid writing look-and-feel-dependent code, you should listen only for high-level events on a compound component such as a combo box. For information about events, including a discussion about high- and low-level events, refer to Writing Event Listeners .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM