Credits

Monday, February 21, 2011

Java's List and Action Events

Event handling in Java makes the program more dynamic and pleasing because of GUI features and capabilities.

Because of GUI various components, we can actually incorporate different events among these components. So, it is important that when we design our interface, we can anticipate possible events like an enter key on text fields, or mouse clicks on buttons, or mouse actions on windows among others.

The program below illustrates the event on list and button and we incorporated ActionEvent and ListSelectionEvent.
 
[+/-] show/hide



/*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 GUIPrefinalEventv2 extends JFrame implements ActionListener, ListSelectionListener
{

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

public GUIPrefinalEventv2() {
super("Exam");
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);
print.addActionListener(this);
setLayout(flo);
add(scroller);
add(print);

setVisible(true);
}



public void valueChanged(ListSelectionEvent e) {
choice=(String) numList.getSelectedValue();
}

public void actionPerformed(ActionEvent a)
{ System.out.println("You chose: "+choice);}

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

AddThis