ActionListener for JComboBox

If I add an ActionListener to JComboBox or ComboBoxEditor I can get notified when user types some text into the combo-box and presses enter.
If I need to get notifications after user types each letter. What should I do ?
I'm stuck with this problem for a long time (I'm a beginner) - any help would be greatly appreciated. Thanks a lot,
--Sergei 

This would be my solution. There may be more but, this is the mest i can do;)
So adding KeyListener.
Let "cb" be your JComboBox object name, what you have to do is:
cb.setEditable(true);
ComboBoxEditor ce = cb.getEditor();
ce.getEditorComponent().addKeyListener(this);
here is the entire example. This progtram will count your keyevents
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example extends Frame implements KeyListener
     private JComboBox cb = new JComboBox();
     private JLabel lab = new JLabel(" ");
     int numb = 0;
     public Example()
          cb.setEditable(true);
          ComboBoxEditor ce = cb.getEditor();
          ce.getEditorComponent().addKeyListener(this);
          setLayout(new FlowLayout());
          add(cb);
          add(lab);
          setSize(200,200);
          show();
     public static void main(String args[])
          new Example();          
     public void keyPressed(KeyEvent e)
     public void keyReleased(KeyEvent e)
               numb ++;
               lab.setText(Integer.toString(numb));
     public void keyTyped(KeyEvent e)

Similar Messages

  • Actionlistener for JCombobox with JCheckbox

    Hi!
    I have written a JComboBox item which holds a checkbox :
    public class CheckComboItem extends JCheckBox{
        private static final long serialVersionUID = 1677961185556377734L;
        public Integer id = 0;
        public CheckComboItem(Integer id, String text, Boolean state) {
            super(text, state);
            this.id = id;
    }This works fine; However i have problems with my action listener, which should change the checkbox' selection state.
    Unfortunately this only works sometimes (randomly) :-(
    public class CheckComboListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JComboBox cb = (JComboBox) e.getSource();
            CheckComboItem store = (CheckComboItem) cb.getSelectedItem();
            store.setSelected((!store.isSelected()));
    }Can you please tell me what i am doing wrong/ how this needs to be improved ?
    Thank you very much!

    You managed to find the Swing forum the last time you posted a Swing question.
    Why didn't you search the Swing forum this time before you posted a question?
    Maybe a JCheckBoxMenuItem will work better.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • How to create a actionListener for individual JButton in a for loop?

    How to create a actionListener for individual JButton in a for loop? Can someone help me?

    Do you mean something like this?:
    JButton tempButton;
    for(int i = 0; i < 10; i++){
         tempButton = new JButton("Button " + String.valueOf(i));
         tempButton.setActionCommand("action" + String.valueOf(i));
         tempButton.addActionListener(this);
         // or tempButton.addActionLister(new ActionListener(){...});
         frame.add(tempButton);
    }

  • Horizontal scrollbar for JComboBox - Not workable under Mac

    By referring to this thread Re: Horizontal scrollbar for JComboBox across multiple look and feel I try to provide horizontal scroll bar for JComboBox to my clients.
    private void adjustScrollBar() {
        //if (this.getItemCount() == 0) return;
        Object comp = this.getUI().getAccessibleChild(this, 0);
        if (!(comp instanceof JPopupMenu)) {
            return;
        JPopupMenu popup = (JPopupMenu) comp;
        // Works fine under Windows and Ubuntu Linux
        // However, in OSX 10.6.4
        // javax.swing.Box$Filler cannot be cast to javax.swing.JScrollPane
        JScrollPane scrollPane = (JScrollPane) popup.getComponent(0);
        scrollPane.setHorizontalScrollBar(new JScrollBar(JScrollBar.HORIZONTAL));
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    }The above code will cause ClassException under OSX 10.6.4. (Works fine for Windows and Linux)
    Any suggestion to resolve this problem. Sorry. I do not have a Mac machine. Hence, can't experiment out much with it.
    Thanks

    The following code works quite well for me.
        private void adjustScrollBar() {
            final int max_search = 8;
            // i < max_search is just a safe guard when getAccessibleChildrenCount
            // returns an arbitary large number. 8 is magic number
            JPopupMenu popup = null;
            for (int i = 0, count = this.getUI().getAccessibleChildrenCount(this); i < count && i < max_search; i++) {
                Object o = this.getUI().getAccessibleChild(this, i);
                if (o instanceof JPopupMenu) {
                    popup = (JPopupMenu)o;
                    break;
            if (popup == null) {
                return;
            JScrollPane scrollPane = null;
            for (int i = 0, count = popup.getComponentCount(); i < count && i < max_search; i++) {
                Component c = popup.getComponent(i);
                if (c instanceof JScrollPane) {
                    scrollPane = (JScrollPane)c;
                    break;
            if (scrollPane == null) {
                return;
            scrollPane.setHorizontalScrollBar(new JScrollBar(JScrollBar.HORIZONTAL));
            scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        }

  • Horizontal scrollbar for JComboBox

    Hi,
    I want to use Horizontal scrollbar for JComboBox which i have used as an editor for table column cell and the matter in drop down list is larger but the width of column of a table is relatively small
    Any suggetions!
    Thanks and regards,
    Nilesh

    Hi,
    I want to use Horizontal scrollbar for JComboBox which i have used as an editor for table column cell and the matter in drop down list is larger but the width of column of a table is relatively small
    Any suggetions!
    Thanks and regards,
    Nilesh

  • Actionlistener - for multiple buttons with similar functionality

    Hi, all:
    I'm working on a calculator program and want to know how to go about making a generic ActionListener for all the functions (i.e. +,-,*,/) so that I don't have to write separate inner classes for each function (i.e. + button, - button, etc.).
    I think this generic class should be created within a method that takes parameters. The parameters are then used within the inner class.
    What I need to know specifically is whether it's possible to pass a string operator symbol (e.g. "+" or "-") as a parameter in the following context:
    class buttonListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    intField1Val + intFieldVal2;
    in this case, the "+" would be the parameter that would change depending on the values provided to the method.
    Can this be done??
    I'd also appreciate any other feedback you can give m,e on this problem (i.e. how to set up the method...basic structure??)
    Thanks!!

    Hi there,
    One way to do this is as follows:
    Button plus = new Button("+");
    Button minus = new Button("-");
    public void actionPerformed(ActionEvent e) {
    String componentHit = e.getActionCommand();
    if (componentHit == "+") {
    doAddMeth(); // implemented elsewhere
    else
    if (componentHit == "-") {
    doSubMeth(); // implemented elsewhere
    ~Bill

  • How to make resizable false for JcomboBox

    hi ,
    I am using JCombobox , but it resizes when length of data inside it is
    increses.I am in trouble because of that.
    Would anybody how to make resizable false for Jcombobox
    --Harish                                                                                                                                                                                                                                                                                                                                                                                   

    Set a preferred size on the combo box, e.g.
    box.setPreferredSize(new Dimension(150,box.getPreferredSize().height));

  • Reusable ActionListener  for logging

    I am trying to develop an reusable ActionListener class called ActionLogger that will log user actions. I would like to use this ActionListener for different buttons in different forms and pages.
    Following scenario:
    User can:
    1. create an new message
    2. change an existing message
    3. acknowledge an message
    4. delete an message
    <h:commandButton action=?createMessage?>
    <f:actionListener type=? ActionLogger? />
    </h:commandButton>
    or
    <h:commandButton action=?deleteMessage?>
    <f:actionListener type=? ActionLogger? />
    </h:commandButton>Each action must be logged with date, userName (full user name) actionName (which button have been clicked.)
    I can get the user Object with firstName and lastName out of the Session Map, but how can I know which button have he clicked on, and if action method in the backing bean was successful or not??
    Any Ideas??
    Thank you in advance:
    Nermin B.

    You can assign ids to the individual commandButton components. When the ActionEvent
    arrives (and is accessible from the listener), it contains the source component - the component that
    caused the event.
    -roger

  • Set border for JComboBox

    i'm trying to change the border for a JComboBox...actually the default border for a JComboBox is null but it is the border for the JScrollPane used by the JComboBox that i want to change....i'm lost as to how to access the JScrollPane that the JComboBox uses so i can change it's border...any ideas?...thanx in advance...

    This might help you see the component you're looking for, but at YATArchivist said, it is a look and feel not a JCombobox componentimport  javax.swing.*;
    import  java.awt.*;
    import  java.util.Random;
    import  java.awt.event.*;
    public class ComboScroll {
      static Random rnd = new Random(); 
      public static void main (String[] args) {
        try {
          if (args.length > 0) {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception ex) {
          ex.printStackTrace();
        final JComboBox combobox = new JComboBox(
          ("foo|bar|baz|" + UIManager.getCrossPlatformLookAndFeelClassName()).split("\\|"));
        combobox.setEditable(true);
        final JFrame frame = new JFrame("ComboScroll");
        frame.getContentPane().add(combobox);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Timer timer = new Timer(800, new ActionListener () {
          public void actionPerformed (ActionEvent e) {
            dumpTree(frame, 0);
            Window[] windows = frame.getOwnedWindows();
            for (int index = 0; index < windows.length; index++) {
              dumpTree(windows[index], 0);
            System.out.println();
        timer.setRepeats(true);
        timer.start();
      static void dumpTree (Component component, int depth) {
        String className = component.getClass().getName();
        System.out.println(indent(depth) + component.getName() + ":" + className);
        if (component instanceof Container) {
          Container container = (Container)component;
          for (int index = 0; index < container.getComponentCount(); index++) {
            dumpTree(container.getComponent(index), depth + 1);
          if (component instanceof JComponent) {
            try {
              ((JComponent)component).setBorder(
                BorderFactory.createTitledBorder(
                  BorderFactory.createMatteBorder(4, 4, 4, 4, new Color(
                    rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))),
                  className.substring(className.lastIndexOf('.') + 1)));
            } catch (Exception ex) {
        if (depth == 0) {
          System.out.println();
      static String indent (int depth) {
        return "                                         ".substring(0, depth * 2);
    }Pete

  • Looking For JComboBox Help

    (Sorry about the lack of rendered tags. I don't know how to use them in this forum.)
    I have a JComboBox (a drop menu) that when opened clears all its items and then adds new items from a list. Whenever the list is augmented (and is small), the JComboBox's display size is too small, and it creates a little scrollbar to accomodate. When the popmenu is closed and reopened, the menu is normal. The problem is that when I open the menu after adding a new item to a list, I have to triple click the JComboBox to make it display correctly.
    Numbers 2 and 4 are unwanted displays.
    <img src="http://img.photobucket.com/albums/v251/Trinithis/dynamicDrive/jcombobox.jpg" />
    I could fix it by having the button itself change the contents of the JComboBox (instead of popupMenuWillBecomeVisible()), but I want to have lazy evaluation for it because in my actual program the ArrayList will have to be sorted each time and the JComboBox will have to re-add all its contents. I suppose this is always an option, but I would like to know how to do it this or some other way.
    <pre>
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    public class GUI extends JFrame implements ActionListener, PopupMenuListener {
         private JButton bAdd = new JButton("Add");
         private JComboBox jcb = new JComboBox();
         private ArrayList<String> items = new ArrayList<String>(10);
         private int addCount = 0;
         public GUI() {
              Container c = this.getContentPane();
              c.setLayout(new FlowLayout());
              bAdd.addActionListener(this);
              jcb.addPopupMenuListener(this);
              c.add(bAdd);
              c.add(jcb);
              this.setSize(200, 100);
              this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              this.setVisible(true);
         public void actionPerformed(ActionEvent e) {
              Object source = e.getSource();
              if(source==bAdd) items.add("Item #" + addCount++);
         public void popupMenuWillBecomeVisible(PopupMenuEvent e){
              Object source = e.getSource();
              if(source==jcb) {
                   jcb.removeAllItems();
                   for(int i=0; i<items.size(); ++i) jcb.addItem(items.get(i));
         public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
         public void popupMenuCanceled(PopupMenuEvent e) {}
         public static void main(String[] args) {
              new GUI();
    </pre>
    Edited by: Trinithis on Sep 21, 2007 11:18 AM
    Edited by: Trinithis on Sep 21, 2007 11:29 AM
    Edited by: Trinithis on Sep 21, 2007 11:33 AM
    Edited by: Trinithis on Sep 21, 2007 11:34 AM

    try it a different way (not using the popupListener)
    public GUI() {
    Container c = this.getContentPane();
    c.setLayout(new FlowLayout());
    bAdd.addActionListener(this);
    jcb.setUI(new javax.swing.plaf.metal.MetalComboBoxUI(){
      protected JButton createArrowButton(){
        JButton btn = super.createArrowButton();
        btn.addMouseListener(new MouseAdapter(){
          public void mousePressed(MouseEvent me){
            if(jcb.getModel().getSize() < items.size()){
              DefaultComboBoxModel model = new DefaultComboBoxModel();
              for(int i=0; i<items.size(); ++i){
                model.addElement(items.get(i));
              jcb.setModel(model);
        return btn;
    //jcb.addPopupMenuListener(this);the tags you're looking for are
    [code]
    paste code here
    [/code]

  • Please Edit Me for JComboBox

    Hi,
    I have a JComboBox. Now i need to alter the a selected item from the list of the JComboBox. After altering the item and when i hit the enter key it should register itself with the JComboBox.
    ok maybe an example will be better.
    Suppose i have three fruits in the JComboBox "Mango","Apple","Grapes". Now when i have given setEditable true for the JComboBox and when i select Mango i should be able to change that to "Banana" and after hitting the enter key the items in the JComboBox should be "Banana","Apple","Grapes".
    I hope i was clear enough. If not i am sorry for tht.
    Any clarification you require feel free to ask.
    Thank You.
    Ehsan

    The attached source code should do the trick...
        UpdatingComboBoxModel m = new UpdatingComboBoxModel(new String[] { "Mango", "Apple", "Grapes" });
        JComboBox cb = new JComboBox(m);
        cb.addActionListener(m);
        cb.setEditable(true);
        public class UpdatingComboBoxModel
            extends DefaultComboBoxModel
            implements ActionListener {
            private int lastIndex;
            public UpdatingComboBoxModel(Object[] items) {
                super(items);
            public void actionPerformed(ActionEvent e) {
                JComboBox cb = (JComboBox) e.getSource();
                if (cb.getModel() != this)
                    throw new Error();
                Object o = cb.getSelectedItem();
                int i = cb.getSelectedIndex();
                if (i == -1) {
                    removeElementAt(lastIndex);
                    insertElementAt(o, lastIndex);
                lastIndex = i;
        }Hope that helps,
    bye

  • Adding actionListener to JComboBox

    Hi there
    I have added actionListener to a JComboBox. I only want the actionPerformed() get called when the user choose the item in the JComboBox, however, it also get called whenever I change the items in the JComboBox.
    I have tried to call the ActionEvent.getID() method to identify the action, however, changing the items and choosing the item give me the same ID - 1001.
    Has anyone got this problem before? How did you solve it?
    Should I use other Listener for listening only the choosing event?
    In advance thanks!
    From
    Edmond

    I had many problems using actionListeners with JComboBox because it gets called all the time, I have had much better luck using mouseListener and the events getClickCount() method for single and double click selections, this avoided many of the problems for me.

  • Keeping id's of list for JCombobox

    Hi,
    i'm filling a JCombobox with database values (Strings) of a table. Every string has an internal ID, which i use to store in other tables.. My problem is the following: i know i can detect what the user selected (getSelectedIndex() and getSelectedValue()), but what does that mean to me. GetSelectedIndex is only a number and GetSelectedValue is the text in de combobox, which i only a text i don't want to store. What i do want to know, is the internal ID behind that value. I don't want to retrieve my database again because i know the String of the table to get the internal ID.
    I solved my problem by extending a JCombobox and keeping track of my internal ID's in a int[], but i don't know if this is the best solution.
    Am I missing something? Is there a very simple solution for my problem?
    Greetz
    Peesjee

    A JComboBox can take as it's model more than just an array or vector or Strings, it can also take an array or vector of objects, and this is important. What is displayed in the combobox is whatever the class's object would display in the class's toString method override. So, if you have a combobox of objects of a class, and you can extract the selected object, you can extract that object's data. As a simple example, see below:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    class Fubar1 extends JPanel
        Fubar1()
            Data[] dataArray =
                new Data("Aaron", 34),
                new Data("Bill", 264),
                new Data("Charlie", 3421),
                new Data("Dennis", 2919),
                new Data("Edward", 9),
            JComboBox combobox = new JComboBox(dataArray);
            combobox.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JComboBox cb = (JComboBox)e.getSource();
                    Data myData = (Data)cb.getSelectedItem();
                    System.out.println(myData.getId()); // display the id of the selected item
            add(combobox);
        private class Data
            String text;
            int id;
            Data(String text, int id)
                this.text = text;
                this.id = id;
            public String getText()
                return text;
            public int getId()
                return id;
            @Override
            public String toString()
                // very important.  this is what shows in combobox
                return text;
        // show the jframe in a thread-safe manner
        private static void createAndShowUI()
            JFrame frame = new JFrame("Fubar");
            frame.getContentPane().add(new Fubar1());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

  • Multiline tooltip for JComboBox items.

    Hi, As the title suggests I'd like to create a multiline tooltip for items in a combobox list.
    I have implemented a multiline tooltip renderer which works perfectly on any component except JComboBox items.
    I have also implemented a ListCellRenderer for a combobox that enables tooltips for the combobox items. Also works perfectly, except that they are single line tooltips.
    The tooltip text is read from an xml file, therefore I have no control on how long the line of text is. Most of the time the text also contains newlines.
    This is the method (overridden from JComponent) added to a subclass of a component so that that component uses the MultiLineToolTip:
        public JToolTip createToolTip() {
            MultiLineToolTip tip = new MultiLineToolTip(this);
            tip.setComponent(this);
            return tip;
        }And this is the ListCellRenderer used on the combobox, so that items have (single-line) tooltips enabled:
        private class ToolTipEnabledComboBoxRenderer extends JLabel implements ListCellRenderer{
             public ToolTipEnabledComboBoxRenderer(){
                  setOpaque(true);
             public Component getListCellRendererComponent(JList list,Object value,
                                                              int index,boolean isSelected,
                                                              boolean cellHasFocus) {
                  String entry = (String)value;
                  if (isSelected || cellHasFocus) {
                       this.setBackground(list.getSelectionBackground());
                       setForeground(list.getSelectionForeground());
                  } else {
                       this.setBackground(list.getBackground());
                       setForeground(list.getForeground());
                  this.setText(entry);
                  if(isSelected || cellHasFocus){
                       if(constraint!=null &&combobox!=null &&
                                   constraint.getType() == Constrained.CONTROLLED_VOCABULARY){
                            String tooltip = ((ControlledVocabulary)constraint).getEntryDescription(entry);
                            if(tooltip==null || tooltip.equals("")){
                                 tooltip="";
                            list.setToolTipText(tooltip);
                  return this;
        }It seems to me that what I have to do is subclass the list used by the combobox and override the createToolTip() method. But how can I set the list used by the combobox? As far as I know the only time I can access the list is in the getListCellRendererComponent() method of the ListCellRenderer, in which the list is a parameter.
    Any ideas?
    Don

    Hello,
    <p>Have you seen this one?</p>
    Francois

  • InputVerifier for JComboBox

    Hi,
    I'm trying to set an InputVerifier for an editable JComboBox using the setInputVerifier() method, to check the input before the JComboBox looses the focus.
    I've tried several things, as for exmaple extending the 'BasicComboBoxEditor' and set the InputVerifier using the protected 'editor' field. But this also does not work!
    Could anyone give me an advice how I could implement a InputVerifier so the content of the JComboBox is checked before it looses the focus? Maybe someone could even point me to an example?!
    Any help is greatly welcome!!
    Regards,
    Zeljko

    JTextField jtf = (JTextField)comboBox.getEditor().getEditorComponent();
    jtf.setInputVerifier(new YourInputVerifier());

Maybe you are looking for