Results 1 to 4 of 4
- 04-16-2010, 09:58 PM #1
Senior Member
- Join Date
- Feb 2010
- Location
- Waterford, Ireland
- Posts
- 748
- Rep Power
- 4
ItemListener problem with JComboBox
I cant get to the bottom of this problem. I have an ItemListener on a JComboBox, the problem is whenever I change the item in the list the listener handler class produces two outputs instead of one. It's like it is running the event twice :confused:
The code in red is printed out twice. Thats the problem basically.
Any help apprecitated
Java Code:import java.awt.GridBagLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.*; public class ItemListenerTrouble { private JFrame frame; private JPanel panel; private JComboBox comboBox; private String[] words={"hello","goodbye","yes","no"}; public ItemListenerTrouble() { frame=new JFrame("Create Your Team"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600,400); panel=new JPanel(); panel.setLayout(new GridBagLayout()); comboBox=new JComboBox(words); ItemHandler ihandle=new ItemHandler(); comboBox.addItemListener(ihandle); panel.add(comboBox); frame.getContentPane().add(panel); frame.setVisible(true); } private class ItemHandler implements ItemListener { public void itemStateChanged(ItemEvent event) { if(event.getSource().equals(comboBox)) { [COLOR="Red"]System.out.println("hello");[/COLOR] } } } public static void main(String args[]) { new ItemListenerTrouble(); } }
-
I'm no pro at this, but what if you change your listener like so:
Java Code:private class ItemHandler implements ItemListener { public void itemStateChanged(ItemEvent event) { if (event.getSource().equals(comboBox)) { if (event.getStateChange() == ItemEvent.SELECTED) { System.out.println("hello. Item Selected: " + comboBox.getSelectedItem()); } } } }
- 04-16-2010, 10:17 PM #3
Senior Member
- Join Date
- Feb 2010
- Location
- Waterford, Ireland
- Posts
- 748
- Rep Power
- 4
Brilliant as always Fubarable!! The funny thing is I always used to use .getSelectedItem() when I wanted the a comboBox selection after a button was pressed. First time using the ItemListener. Right back to the project :D
Thanks Fubarable
-
I wish it were brilliant -- but it's from the tutorial: How to Write an Item Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)
Similar Threads
-
Serious Problem with JComboBox
By Plissken in forum New To JavaReplies: 3Last Post: 02-02-2010, 10:48 AM -
Accessibility of JComboBox problem
By abedules78 in forum AWT / SwingReplies: 0Last Post: 12-26-2008, 01:11 PM -
Problem with JComboBox and Jlist
By java_fun2007 in forum New To JavaReplies: 2Last Post: 05-07-2008, 08:58 PM -
Demonstrating the ItemListener
By Java Tip in forum java.awtReplies: 0Last Post: 04-23-2008, 08:25 PM -
How to use ItemListener for CheckBox class
By Java Tip in forum javax.swingReplies: 0Last Post: 04-23-2008, 08:18 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks