Tuesday, November 4, 2008

ListApplet

// This applet creates a scrolling list with several choices and
// informs you of selections and deselections using a label.
//

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

public class ListApplet extends Applet {

Label listStatus;
List myList;

public void init() {

// First, create the List
myList = new List(7, true);

// Now add items to the list

for (int i=0;i<100; i++)
myList.add("Item "+Integer.toString(i));

// Set Item 13 to be selected
myList.select(13);

// Finally, add the list to the applet
add(myList);

//Create a label to show the last event that occurred
listStatus = new Label("Selected entry");
add(listStatus);

//Add object mouse listener to List
myList.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent evt) {
//Get double click item
String clickItem= evt.getActionCommand();

//Update status
listStatus.setText(clickItem+" Double clicked ");

}
});


//Add object Item change listener to List using inner class
myList.addItemListener( new ItemListener(){

public void itemStateChanged (ItemEvent evt){
String Selection;
String selItem;
int selIndex;

if (evt.getStateChange() == ItemEvent.SELECTED){
// selection is the index of the selected item
selIndex = ((Integer)evt.getItem()).intValue();
selItem = myList.getItem(selIndex);

// use getItem to get the actual item.
Selection = selItem +" Selected " ;
// Update the label
listStatus.setText(Selection);
} else {
// If this is a deselection, get the deselected item
// selection is the index of the selected item
selIndex = ((Integer)evt.getItem()).intValue();
selItem = myList.getItem(selIndex);
// use getItem to get the actual item.
Selection = selItem+" Deselected " ;

// Update the label

listStatus.setText(Selection);

}
}
});
}
}