Kyle Harris
Kyle Harris

Reputation: 137

JComboBox ItemListener error

Looking at adding event listeners to JComboBoxes. Ive done the usual window etc. Created a new JComboBox and then .addItem() islands into it. I have then attempted to use .addItemListener(this) on my newly created combobox But theres a problem, its mentioning abstract class which means i have not done something. Can anyone see where ive gone wrong?

Ive tried .addItemListener(this) on the individual entries and that did not work. Ive tried declaring the JComboBox inside and outside of the constructor.

It may be worth noting the method itemStateChange is from the book, I have had to build around that block.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class ComboBoxPractice extends JFrame implements ItemListener
{
    //create islands          
    JLabel selection = new JLabel();       
    JComboBox islands = new JComboBox();  
    
    public ComboBoxPractice()
    {
    // set a window
        super("action");
        setSize(300,100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    // set a container
        Container content = getContentPane();
        FlowLayout layout = new FlowLayout();
        content.setLayout(layout);
    //add item listener   
        islands.addItemListener(this);
    // add items to list
        islands.addItem("Corfu");
        islands.addItem("Crete");
        islands.addItem("Canada");
        islands.addItem("Canary Islands");
    //add island and label to container  
        content.add(islands);   
        content.add(selection);
    }
    
    public void itemStateChange(ItemEvent event)
    {
    String choice = event.getItem().toString();
    selection.setText("chose" + choice);
    }
}

The exact error

Upvotes: 1

Views: 216

Answers (1)

3kings
3kings

Reputation: 838

@Override
public void itemStateChanged(ItemEvent event)
{
    String choice = event.getItem().toString();
    selection.setText("chose" + choice);
}

Try changing it to that. with the @Override on top. This then doesn't throw an error for me and works.

Upvotes: 1

Related Questions