LAB ACTIVITY 3B
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 3B
Activity Outcome: Student know how to create event handling program for button.
CREATE New Project name as TestButton
i. Type the following code:
package testbutton;
import java.awt.*;
import javax.swing.*;
public class TestButton extends JFrame{
JButton butang = new JButton ();
JButton butang2 = new JButton (" RED ");
JLabel stmt = new JLabel("This is a label");
TestButton()
{
setTitle("Button");
setLayout(new FlowLayout());
butang.setText(" YELLOW ");
stmt.setFont(new Font("Arial",Font.BOLD,24));
add (butang);
add (butang2);
add (stmt);
setSize(300,300);
setVisible(true);
}
public static void main(String[] args) {
TestButton btg=new TestButton();
}
}
ii. Declaration of the event handler class
a) Add package java.awt.event.*;
b) implements ActionListener.
DON'T WORRY about error line under text TestButton. 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 , add following code
butang.addActionListener(this);
butang2.addActionListener(this);
example image:
iv. Implements the methods in the listener interface.
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==butang)
stmt.setForeground(Color.YELLOW);
else if (e.getSource()==butang2)
stmt.setForeground(Color.RED);
}
example image:
FULL CODE & EXAMPLE GUI OUTPUT :
package testbutton;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TestButton extends JFrame implements ActionListener{
JButton butang = new JButton ();
JButton butang2 = new JButton (" RED ");
JLabel stmt = new JLabel("This is a label");
TestButton()
{
setTitle("Button");
setLayout(new FlowLayout());
butang.setText(" YELLOW ");
stmt.setFont(new Font("Arial",Font.BOLD,24));
butang.addActionListener(this);
butang2.addActionListener(this);
add (butang);
add (butang2);
add (stmt);
setSize(300,300);
setVisible(true);
}
public static void main(String[ ] args) {
TestButton btg=new TestButton();
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==butang)
stmt.setForeground(Color.YELLOW);
else if (e.getSource()==butang2)
stmt.setForeground(Color.RED);
}
}
OUTPUT : (Click mouse Button YELLOW or RED to see the different for the Label 'This is a label' )