// Scott DeRuiter 3/6/2003
// HearMouseMotion.java
// This is a simple example of implementing a MouseMotionListener in
// a Swing Applet.
// 3/13/2013 Greenstein: Changed from applet to JFrame
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class HearMouseMotion implements MouseMotionListener
{
private int xpos, ypos, rect1xco, rect1yco, rect1width, rect1height;
private boolean rect1Active, initialdraw;
private JFrame frame;
private MyPanel canvas;
public HearMouseMotion ()
{
xpos = ypos = 0;
rect1xco = rect1yco = 20;
rect1width = 100;
rect1height = 60;
rect1Active = false;
initialdraw = true;
}
public static void main(String[] args)
{
HearMouseMotion hmm = new HearMouseMotion();
hmm.Run();
}
public void Run()
{
// Create a frame to hold everything
frame = new JFrame ("Hear Mouse");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setBackground(Color.black); // only needed if frame is larger than panel
// Define panel to draw on
canvas = new MyPanel(); // create a panel to draw on
canvas.setBackground(Color.lightGray);
canvas.addMouseMotionListener(this); // connects the MouseMotionListerner to the panel window
// Put frame together
frame.getContentPane().add(canvas); // puts panel on frame
frame.setVisible(true);
}
class MyPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if ( rect1Active )
g.setColor ( Color.blue );
else
g.setColor ( Color.cyan );
g.fillRect ( rect1xco, rect1yco, rect1width, rect1height );
g.setColor ( Color.red );
if ( !initialdraw )
g.drawString ( "(" + xpos + "," + ypos + ")", xpos, ypos );
}
}
public void mouseMoved ( MouseEvent e )
{
xpos = e.getX();
ypos = e.getY();
if (xpos > rect1xco && xpos < rect1xco + rect1width
&& ypos > rect1yco && ypos < rect1yco + rect1height )
rect1Active = true;
else
rect1Active = false;
initialdraw = false;
canvas.repaint();
}
public void mouseDragged ( MouseEvent e ) {}
}
Back to Lesson 25 Examples
Back to Java Main Page