LAB ACTIVITY 3C
EVENT HANDLING
EVENT HANDLING
Learning Outcomes
By the end of this lab, students should be able to :
Write Java programs using Event Handling
Write Java programs using Event Handling with GUI Components
Hardware/ Software : Personal Computer, Java Development Kit version X.x.x., NetBeans IDE 12.0
LAB ACTIVITY 3C
Activity Outcome: Student know how to create event handling program for combo box.
CREATE New Project name as TestComboBox
i. Type the following code:
package testcombobox;
import java.awt.*;
import javax.swing.*;
public class TestComboBox extends JFrame{
JComboBox listComboBox;
String names[] ={"January","February","March","April","May","June","July","Ogos",
"September","October","November","December"};
public TestComboBox()
{
setLayout( new FlowLayout() );
setTitle("Combo Box Example");
listComboBox = new JComboBox( names );
listComboBox.setMaximumRowCount( 12 );
add( listComboBox );
setSize( 350, 100 );
setVisible( true );
}
public static void main( String args[] )
{
TestComboBox application = new TestComboBox();
}
}
ii. Declaration of the event handler class
a) Add package java.awt.event.*;
b) implements ActionListener.
DON'T WORRY about error line under text TestComboBox. The reasons is not override abstract method actionPerformed (ActionEvent) in ActionListener. After when add actionPerformed, error line will be disappear.
iii. Registers an instance of the event handler class
listComboBox.addActionListener(this);
example image:
iv. Implements the methods in the listener interface.
public void actionPerformed(ActionEvent e)
{
int value = JOptionPane.showConfirmDialog(null, "Did you choose..."
+listComboBox.getSelectedItem()+"?", "MONTH",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
}
example image:
FULL CODE & EXAMPLE GUI OUTPUT :
package testbutton;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TestComboBox extends JFrame implements ActionListener{
JComboBox listComboBox;
String names[] ={"January","February","March","April","May","June","July","Ogos",
"September","October","November","December"};
public TestComboBox()
{
setLayout( new FlowLayout() );
setTitle("Combo Box Example");
listComboBox = new JComboBox( names );
listComboBox.setMaximumRowCount( 12 );
add( listComboBox );
listComboBox.addActionListener(this);
setSize( 350, 100 );
setVisible( true );
}
public static void main( String args[] )
{
TestComboBox application = new TestComboBox();
}
public void actionPerformed(ActionEvent e)
{
int value = JOptionPane.showConfirmDialog(null, "Did you choose..."
+listComboBox.getSelectedItem()+"?", "MONTH",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
}
}
OUTPUT : (Select list at ComboBox to show popUp box 'Did you choose...' )