// Scott DeRuiter 3/6/2003
// HearMouse.java
// This is a simple example of implementing a MouseListener 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 HearMouse implements MouseListener
{
private int xpos, ypos, rect1xco, rect1yco, rect1width, rect1height;
private boolean mouseEntered, rect1Clicked, initialdraw;
private JFrame frame;
private MyPanel canvas;
public HearMouse ()
{
xpos = ypos = 0;
rect1xco = rect1yco = 20;
rect1width = 100;
rect1height = 60;
initialdraw = true;
mouseEntered = rect1Clicked = false;
}
public static void main(String[] args)
{
HearMouse hm = new HearMouse();
hm.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.addMouseListener(this); // connects the MouseListerner 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);
g.setColor ( Color.blue );
g.fillRect ( rect1xco, rect1yco, rect1width, rect1height );
g.setColor ( Color.red );
if ( !initialdraw )
g.drawString ( "(" + xpos + "," + ypos + ")", xpos, ypos );
if ( initialdraw )
g.drawString ( "Press the mouse somewhere in the applet", 20, 120 );
else if ( rect1Clicked )
g.drawString ( "You pressed in the Rectangle ", 20, 120 );
else
g.drawString ( "You pressed outside of the Rectangle", 20, 120 );
if ( mouseEntered )
g.drawString ( "Mouse is in the Applet area", 20, 160 );
else
g.drawString ( "Mouse is outside the Applet area", 20, 160 );
}
}
public void mouseClicked ( MouseEvent e ) {}
public void mousePressed ( MouseEvent e )
{
xpos = e.getX();
ypos = e.getY();
if (xpos > rect1xco && xpos < rect1xco + rect1width
&& ypos > rect1yco && ypos < rect1yco + rect1height )
rect1Clicked = true;
else
rect1Clicked = false;
initialdraw = false;
canvas.repaint();
}
public void mouseReleased ( MouseEvent e ) {}
public void mouseEntered ( MouseEvent e )
{
mouseEntered = true;
canvas.repaint();
}
public void mouseExited ( MouseEvent e )
{
mouseEntered = false;
canvas.repaint();
}
}
Back to Lesson 25 Examples
Back to Java Main Page