I am trying to get the ItemListener to work on this program. I keep getting an error that says the method getSelectedItem cannont be found and cannot figure out how to fix it.

import java.awt.*;
import java.awt.event.*;

public class Buttons extends Frame implements ActionListener, ItemListener
{
    public Buttons()
    {
        //set the layout
        setLayout(new BorderLayout(20,5));
        setBackground(Color.red);

        //Add buttons
        Button north = new Button("Red");
        Button south = new Button("Yellow");
        Button east = new Button("Cyan");
        Button west = new Button("Magenta");
        Choice colors = new Choice();
        colors.addItemListener(this);

        add(north, BorderLayout.NORTH);
            north.addActionListener(this);
        add(south, BorderLayout.SOUTH);
            south.addActionListener(this);
        add(east, BorderLayout.EAST);
            east.addActionListener(this);
        add(west, BorderLayout.WEST);
            west.addActionListener(this);
        add(colors, BorderLayout.CENTER);
            colors.add("Red");
            colors.add("Yellow");
            colors.add("Cyan");
            colors.add("Magenta");


        //override the windowClosing event
        addWindowListener(
            new WindowAdapter()
                {
                public void windowClosing(WindowEvent e)
                    {
                       System.exit(0);
                    }
                }
        );

    }

    public static  void main(String args[])
    {
        // set frame properties

        Buttons f = new Buttons();
        f.setTitle("Border Application");
        f.setBounds(200,200,300,300);
        f.setVisible(true);
   }

   public void actionPerformed(ActionEvent e)
   {
       String arg = e.getActionCommand();

       if(arg == "Yellow")
       {
           setBackground(Color.yellow);
       }
   }

   public void itemStateChanged(ItemEvent ie)
   {
       String arg = ie.getSelectedItem();
   }
}

i think getSelectedItem() mothos not available in the ItemEvent Class

if you can replace getItem() method instead of that i think that error can be removed

try it once........

i don't know whether that is your actual requirement or not

please check it once

  • for why reason you using AWT to use Swing instead

  • then Choice should be JComboBox, (Frame/JFrame, Button/JButton)

  • add ItemListener to JComboBox

  • ItemListener always fired twice events, SELECTED and DESELECTED,

  • can to determine, test if ITEM_STATE_CHANGED only

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.