The MouseListener interface allows you to retrieve mouse events. A program implements this interface in a manner similar to the WindowListener interface. For example, the following program creates a JFrame and outputs the X and Y coordinates of any mouse clicks within the JFrame. The MouseListener interface requires the implementing class to define the mouseClicked, mouseEntered, mousePressed, mouseReleased, and mouseExited methods. In the example, only the mouseClicked method has been completed.
import javax.swing.JFrame;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
public class MouseDemo extends JFrame implements MouseListener
{
public void mouseClicked (MouseEvent e)
{
System.out.println(e.getX() + " " + e.getY());
}
public void mouseEntered (MouseEvent e) {}
public void mousePressed (MouseEvent e) {}
public void mouseReleased (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
public MouseDemo()
{
super();
setSize(600,400);
setTitle("Mouse Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMouseListener(this); // Add listener for this object
}
public static void main(String[] args)
{
MouseDemo m = new MouseDemo();
m.setVisible(true);
}
}
Modify this program to create a simple drawing program. When the mouse button is clicked, a solid circle with a radius of three pixels should be drawn in the Jframe centered at the mouse coordinates. Draw the circle in the color of your choice. Make sure that the drawing is correctly redrawn if the JFrame is minimized and then displayed again.
Sorry the answer is not available at the moment…
If you are able to find the answer, please make sure to post it here. So that your Juniors have smile on their lips and feel happy.
Spread the 'tradition of sharing'.