Advanced Java Programming Practical 11
Question 1
Write a program to change the background color of Applet when user performs events using Mouse
MouseDemo.java
Java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class MouseDemo extends Applet implements MouseListener
{
public void init()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent me)
{
setBackground(Color.red);
repaint();
}
public void mouseEntered(MouseEvent me)
{
setBackground(Color.green);
repaint();
}
public void mouseExited(MouseEvent me)
{
setBackground(Color.blue);
repaint();
}
public void mousePressed(MouseEvent me)
{
setBackground(Color.yellow);
repaint();
}
public void mouseReleased(MouseEvent me)
{
setBackground(Color.pink);
repaint();
}
}
/* <applet code="MouseDemo" width=300 height=300></applet> */
Output

Question 2
Write a program to count the number of clicks performed by the user in a Frame window
CountDemo.java
Java
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class CountDemo extends JFrame implements MouseListener
{
int count=0;
Label l;
CountDemo()
{
l=new Label();
l.setBounds(50,50,200,50);
addMouseListener(this);
add(l);
setLayout(null);
setSize(500,300);
setTitle("Mouse click count");
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void mouseClicked(MouseEvent e)
{
count++;
l.setText("Click count: "+count);
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public static void main(String args[])
{
CountDemo cd=new CountDemo();
}
}
Output

Question 3
Write a program to demonstrate the use of mouseDragged and mouseMoved method of MouseMotionListener
MotionDemo.java
Java
import javax.swing.*;
import java.awt.event.*;
public class MotionDemo extends JFrame implements MouseMotionListener
{
JLabel jl;
MotionDemo()
{
jl=new JLabel();
jl.setBounds(50,50,200,50);
addMouseMotionListener(this);
add(jl);
setLayout(null);
setSize(500,300);
setTitle("Mouse Motion Demo");
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void mouseDragged(MouseEvent e)
{
jl.setText("Mouse Dragged");
}
public void mouseMoved(MouseEvent e)
{
jl.setText("Mouse Moved");
}
public static void main(String args[])
{
MotionDemo md=new MotionDemo();
}
}
Output
