Monday, August 5, 2013

ItemListener

ItemListener is an interface to receive item event that is generated by Checkbox, Choice, and List components when an item of the Checkbox object is turned on or turned of or when an item of the Choice or List object is selected.

A class that wants to receive the item event must implement the ItemListener interface. Then listener is registered with the source component by using the addItemListener(ItemListener listener) method. The ItemListener has the itemStateChanged(ItemEvent e) method that need to be overridden to cause an action to happen.

Example:

import java.awt.Choice;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame implements ItemListener{
InterfaceShow(String title){
setTitle(title);
setLayout(new FlowLayout());
changeSize("200x150");
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Choice listsizes=new Choice();
listsizes.addItemListener(this);
listsizes.add("200x150");
listsizes.add("300x250");
listsizes.add("400x350");
listsizes.add("500x350");
listsizes.add("600x450");
listsizes.add("700x450");
listsizes.add("800x550");
add(new Label("Select window size:"));
add(listsizes);
validate();
}

public void changeSize(String d){
String[] di=d.split("x");  
  setSize(Integer.parseInt(di[0]),Integer.parseInt(di[1]));
}
public void itemStateChanged(ItemEvent e){

changeSize(e.getItem().toString());
}

}
public class ItemListenerTest {
public static void main(String[] args){
new InterfaceShow("ItemListener");

}
}
ItemListener ItemEvent

In the example code above,  the Choice component, listsizes is used to store strings. Each string represents a dimension (width and height) of the window. When the user selects a dimension from the Choice component, an action happens. The action to perform is resetting the size or dimension of the window. The code of the action is written in the itemStateChanged method. Since each dimension is a string that contains width and height, we need to separate it in to integer values that represent a width and height. Then the setSize method is used to resize the size of the window.

No comments:

Post a Comment