Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Problem with Key listener to JComboBox

  1. #1
    Member
    Join Date
    Sep 2011
    Location
    Nanuet, NY USA
    Posts
    33
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Problem with Key listener to JComboBox

    Hi,
    I am trying to add a key Listener to a JComboBox so that when you hit the delete key, it deletes the item selected from the Combo box. Here is the code that registers the listener to the combo box.

    jcboCountries.addKeyListener(new KeyAdapter() {
    	  public void keyPressed(KeyEvent e) {
    	    System.out.println("In key pressed");
    	    if (e.getKeyCode() == KeyEvent.VK_DELETE){
    		  System.out.println("Delete key hit");
    		  Object item = model.getSelectedItem();
    		  jcboCountries.removeItem(item); 
    		}
    	  }
    	});

    I also added this line to set the combo box focus.

    jcboCountries.setFocusable(true);

    But when I hit the delete button nothing happens. The println lines don't print. Nothing.

    Any help is appreciated.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem with Key listener to JComboBox

    Does the JComboBox have the focus? That determines what component gets key events.

  3. #3
    Member
    Join Date
    Sep 2011
    Location
    Nanuet, NY USA
    Posts
    33
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Problem with Key listener to JComboBox

    Quote Originally Posted by Norm View Post
    Does the JComboBox have the focus? That determines what component gets key events.
    I thought so. I thought jcboCountries.setFocusable(true) was supposed to do that. Am I using the wrong method?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem with Key listener to JComboBox

    Add a focus listener to it and see if it gets the focus.

    Also when using Adapters, be sure to use the @Override notation. The compiler is happy to let you add any methods you want. You want to be sure you are overriding one of the Adapter's methods and not adding a new one.
    Last edited by Norm; February 10th, 2012 at 09:35 PM.

  5. #5
    Member
    Join Date
    Sep 2011
    Location
    Nanuet, NY USA
    Posts
    33
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Problem with Key listener to JComboBox

    Quote Originally Posted by Norm View Post
    Add a focus listener to it and see if it gets the focus.

    Also when using Adapters, be sure to use the @Override notation. The compiler is happy to let you add any methods you want. You want to be sure you are overriding one of the Adapter's methods and not adding a new one.
    I added the focus listener but nothing happened so it is not getting focus. Here is my entire code.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    public class Exercise35_13 extends JApplet {
      private final static int NUMBER_OF_NATIONS = 7;
      private String[] nations = new String[] {"Denmark",
        "Germany", "China", "India", "Norway", "UK", "US"};
      private ImageIcon[] icons = new ImageIcon[NUMBER_OF_NATIONS];
      private ImageIcon[] bigIcons = new ImageIcon[NUMBER_OF_NATIONS];
     
      // Create a combo box model
      private DefaultComboBoxModel model = new DefaultComboBoxModel();
     
      // Create a combo box with the specified model
      private JComboBox jcboCountries = new JComboBox(model);
     
      // Create a list cell renderer
      private MyListCellRenderer renderer = new MyListCellRenderer();
     
      // Create a label for displaying iamge
      private JLabel jlblImage = new JLabel("", JLabel.CENTER);
     
      /** Construct the applet */
      public Exercise35_13() {
        // Load small and large image icons
        for (int i = 0; i < NUMBER_OF_NATIONS; i++) {
          icons[i] = new ImageIcon(getClass().getResource(
            "/image/flagIcon" + i + ".gif"));
          model.addElement(new Object[]{icons[i], nations[i]});
     
          bigIcons[i] = new ImageIcon(getClass().getResource(
            "/image/flag" + i + ".gif"));
        }
     
        // Set list cell renderer for the combo box
    	jcboCountries.setFocusable(true);
        jcboCountries.setRenderer(renderer);
        jlblImage.setIcon(bigIcons[0]);
        add(jcboCountries, java.awt.BorderLayout.NORTH);
        add(jlblImage, java.awt.BorderLayout.CENTER);
     
        // Register listener
        jcboCountries.addActionListener(new ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent e) {
            jlblImage.setIcon(bigIcons[jcboCountries.getSelectedIndex()]);
          }
        });
    	// Register listener
    	jcboCountries.addKeyListener(new KeyAdapter() {
    	  @Override
    	  public void keyPressed(KeyEvent e) {
    	    System.out.println("In key pressed");
    	    if (e.getKeyCode() == KeyEvent.VK_DELETE){
    		  System.out.println("Delete key hit");
    		  Object item = model.getSelectedItem();
    		  jcboCountries.removeItem(item); 
    		}
    	  }
    	});
    	// Register listener
    	jcboCountries.addFocusListener(new FocusAdapter() {
    	  public void focusGained(FocusEvent e) {
    	    System.out.println("Focus Gained");
     
    	  }
    	});
      }
     
      /** Main method */
      public static void main(String[] args) {
        ComboBoxCellRendererDemo applet = new ComboBoxCellRendererDemo();
        JFrame frame = new JFrame();
        //EXIT_ON_CLOSE == 3
        frame.setDefaultCloseOperation(3);
        frame.setTitle("ComboBoxCellRendererDemo");
        frame.getContentPane().add(applet, BorderLayout.CENTER);
        applet.init();
        applet.start();
        frame.setSize(400,320);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    }

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem with Key listener to JComboBox

    the posted code does not compile without changes.

    Using the code as an applet, it works for me. Running it in AppletViewer:

    Focus Gained
    key pressed e=java.awt.event.KeyEvent[KEY_PRESSED,keyCode=127,keyText=Delete,keyChar=Del ete,keyLocation=KEY_LOCATION_STANDARD] on javax.swing.JComboBox[,0,0,500x25,layout=javax.swing.plaf.metal.MetalCom boBoxUI$MetalComboBoxLayoutManager,alignmentX=0.0, alignmentY=0.0,border=,flags=16777544,maximumSize= ,minimumSize=,preferredSize=,isEditable=false,ligh tWeightPopupEnabled=true,maximumRowCount=8,selecte dItemReminder=[Ljava.lang.Object;@b6548]
    Delete key hit
    key pressed e=java.awt.event.KeyEvent[KEY_PRESSED,keyCode=10,keyText=Enter,keyChar=Enter ,keyLocation=KEY_LOCATION_STANDARD] on javax.swing.JComboBox[,0,0,500x25,layout=javax.swing.plaf.metal.MetalCom boBoxUI$MetalComboBoxLayoutManager,alignmentX=0.0, alignmentY=0.0,border=,flags=16777544,maximumSize= ,minimumSize=,preferredSize=,isEditable=false,ligh tWeightPopupEnabled=true,maximumRowCount=8,selecte dItemReminder=[Ljava.lang.Object;@1358f03]

  7. The Following User Says Thank You to Norm For This Useful Post:

    kc120us (February 11th, 2012)

  8. #7
    Member
    Join Date
    Sep 2011
    Location
    Nanuet, NY USA
    Posts
    33
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Problem with Key listener to JComboBox

    Wow, you are right. I put the class file in an html page and it worked fine as an applet. But it does not run as a standalone application.
    Thanks

Similar Threads

  1. Problem with reset on JComboBox
    By WorkingMan in forum AWT / Java Swing
    Replies: 4
    Last Post: April 25th, 2013, 12:19 PM
  2. add action listener problem
    By mdhmdh100 in forum AWT / Java Swing
    Replies: 5
    Last Post: February 5th, 2012, 02:53 AM
  3. Key Listener problem!
    By DouboC in forum What's Wrong With My Code?
    Replies: 1
    Last Post: January 17th, 2012, 07:47 PM
  4. [SOLVED] Having Problem with my JComboBox
    By dazzl3r in forum What's Wrong With My Code?
    Replies: 4
    Last Post: December 9th, 2010, 12:03 AM
  5. Problem getting selected item as string from JComboBox
    By lost in forum AWT / Java Swing
    Replies: 1
    Last Post: October 26th, 2010, 03:22 AM