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

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 developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.