I have seen these two methods of using ItemListener. I am curios which is better and why. What are the differences?

ItemListener a;
Choice ce = new Choice();
ce.addItemListener(a);



ItemListener itemlistener = new ItemListener();
itemlistener.handle = checkboxmenuitem;
checkboxmenuitem.addItemListener(itemlistener);

Recommended Answers

Don't forget that Java 8 has been out since last Spring, so you should be using a Lambda expression instead of that clunky anonymous inner class, eg

c.addItemListener(ie -> System.out.println("Your choice was" + c.getSelectedItem()));

Jump to Post

All 2 Replies

I looked into this, but i cannot find a "handle" method for interface ItemListener at all. The oracle documentation says it contains only 1 method : http://docs.oracle.com/javase/7/docs/api/java/awt/event/ItemListener.html
Also the second choice's listener is attached to a checkbox not a choice so they are inherently different right away...

To implement an itemlistener interface you would have implement its abstract method like:

ItemListener itemlistener = new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {

            }
        };

A good examples of a complete implementation of an itemlistener attached to a radio button can be found here : http://examples.javacodegeeks.com/desktop-java/awt/event/itemlistener-example/

So i cannot say which is better, but if i had to choose how i would add an item listener to a choice i would probably do something like :

Choice c=new Choice();
c.add("First Choice");
frame.add(c);

c.addItemListener(new ItemListener()
 {
        public void itemStateChanged(ItemEvent ie)
        {
        System.out.println("Your choice was"+c.getSelectedItem());
        }
 });

Im not really sure i can answer the question without knowing what the handle method does, but i hope this helps in some way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.