LAB ACTIVITY 3I
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 3I
Activity Outcome: Student know how to create event handling program for MouseMotionListener.
CREATE New Project name as Painter
i. Type the following code:
package painter;
import java.awt.*;
import javax.swing.*;
public class Painter extends JFrame{
private int pointCount = 0;
private Point points[] = new Point[1000];
public Painter(){
super("A simple paint program");
getContentPane().add(new JLabel("Drag the mouse to draw"),
BorderLayout.SOUTH);
setSize(300, 150);
setVisible(true);
}
public static void main(String args[]){
Painter application = new Painter();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
ii. Declaration of the event handler class
a) Add package java.awt.event.*;
b) addMouseMotionListener
addMouseMotionListener(
new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent event)
{
if (pointCount < points.length)
{
points[pointCount] = event.getPoint();
++pointCount;
repaint();
}
}
} );
example image:
iii. Create effect public class using by mouse
public void paint(Graphics g){
super.paint(g);
for(int i=0; i< points.length && points[i] != null; i++)
g.fillOval(points[i].x, points[i].y, 4, 4);
}
example image:
FULL CODE & EXAMPLE GUI OUTPUT :
package painter;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Painter extends JFrame{
private int pointCount = 0;
private Point points[] = new Point[1000];
public Painter(){
super("A simple paint program");
getContentPane().add(new JLabel("Drag the mouse to draw"),
BorderLayout.SOUTH);
addMouseMotionListener(
new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent event)
{
if (pointCount < points.length)
{
points[pointCount] = event.getPoint();
++pointCount;
repaint();
}
}
} );
setSize(300, 150);
setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
for(int i=0; i< points.length && points[i] != null; i++)
g.fillOval(points[i].x, points[i].y, 4, 4);
}
public static void main(String args[]){
Painter application = new Painter();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
OUTPUT : (Move and Click mouse on Frame to show graphic line)