Results 1 to 2 of 2
Like Tree1Likes
  • 1 Post By DarrylBurke

Thread: JComboBox fires selection ActionEvent when I initialize it and I don't want it to.

  1. #1
    msphelix is offline Member
    Join Date
    Aug 2012
    Posts
    9
    Rep Power
    0

    Default JComboBox fires selection ActionEvent when I initialize it and I don't want it to.

    Hi, I am comfortable using JComboBox. I am now using an ActionListener to catch selection change ActionEvents and do something with them in the actionPerformed() that handles the event (get the selected index, get the element at the selected index in an array of objects, and display its values in a JOptionPane -will be displayed in components when I get it working). The problem is JComboBox.addItem() fires a selection change event when I am initializing the combo. When this happens, the selected index is either 0 (the first item is selected) or -1 (invalid). So while the combo is being initializing the combo and before the GUI displays, the program either displays the first item or crashes because the index is invalid. There is a similar problem with dynamically adding or deleting an item (JComboBox.removeItemAt()). I can fix this by not adding the ActionListener until the combo is initialized and removing the ActionListener before an add or delete and (re)adding it after the add or delete, but isn't there a better way?
    Thanks.

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,193
    Rep Power
    19

    Default Re: JComboBox fires selection ActionEvent when I initialize it and I don't want it to

    For a listener to ignore programmatic changes, I usually use a boolean flag.

    db
    sehudson likes this.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. Replies: 11
    Last Post: 04-11-2012, 05:57 PM
  2. What does (this) and ActionEvent e mean?
    By africanhacker in forum New To Java
    Replies: 3
    Last Post: 02-06-2011, 05:08 PM
  3. Replies: 1
    Last Post: 11-23-2010, 06:26 PM
  4. Replies: 2
    Last Post: 12-10-2009, 01:58 PM
  5. ActionEvent example
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 03-11-2008, 11:00 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •