by Dinesh Thakur Category: Swing

Item events occur when a user selects a choice item, a checkbox menu item or a list item. Objects representing item events are created from the ItemEvent class.

The corresponding listener interface for ItemEvent class is ItemListener. Each listener for ItemEvent should implement the ItemListener interface. This listener defines the following method to handle ItemEvent generated by a user interface component.

void itemStateChanged(ItemEvent e)

It is called when the selected item changes.

import javax.swing.*;

import java.awt.*;   
import java.awt.event.*;
class ItemListenerExample extends JFrame implements ItemListener
{
    JLabel lblData;
    JComboBox cbofont;
    ItemListenerExample()
    {
        setLayout(new FlowLayout());
        lblData = new JLabel("Font Displayed");
        String[] fontData ={"Arial","Courier New", "Arial Black", "Times New Roman"};
        cbofont = new JComboBox(fontData);
        cbofont.addItemListener(this);
        add(lblData);
        add(cbofont);
    }
     public void itemStateChanged(ItemEvent e)
    {
         String fontName=(String)cbofont.getSelectedItem();
         Font font = new Font(fontName,Font.PLAIN,12);
         lblData.setFont(font);
    }
}
class ItemListenerJavaExample
{
   public static void main(String args[])
   {
      ItemListenerExample frame = new ItemListenerExample();
      frame.setTitle("ItemListener Java Example");
      frame.setBounds(200,150,180,150);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setResizable(false);
      frame.setVisible(true);
  }
}

ItemListener in Java Swing Examples



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles