Credits

Monday, February 21, 2011

Java's List Event

You can actually choose an item from a list with a double click. With this, we invoke a list event through the ListSelectionEvent type.  A list may have three selection modes: SINGLE SELECTION, SINGLE INTERVAL and MULTIPLE INTERVAL.  The default  selection mode is Multiple Interval allowing us to select several contiguous cells or items from our list.

I have revised the previous list and action event simply through a selection on the list to invoke the event with a label of the chosen item.
[+/-] show/hide

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Rose
*/


/*answer to the prefinal exam hands - on exam*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;

public class GUIPREFINEVENTV3 extends JFrame implements ListSelectionListener
{

String[] numbers={" Zero "," One "," Two "," Three "," Four "," Five "," Six "," Seven "," Eight "," Nine "};
JList numList=new JList(numbers);

JLabel xlabel = new JLabel();
String choice;

public GUIPREFINEVENTV3() {
super("List Event");
setSize(100, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

FlowLayout flo = new FlowLayout();
numList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
numList.addListSelectionListener(this);

JScrollPane scroller=new JScrollPane(numList);
setLayout(flo);
add(scroller);
add(xlabel);
setVisible(true);

}



public void valueChanged(ListSelectionEvent e) {
choice=(String) numList.getSelectedValue();
xlabel.setText("You chose: "+choice);
}


public static void main(String[] arguments) {
GUIPREFINEVENTV3 app = new GUIPREFINEVENTV3();
}
}

AddThis