Charles Bell
Posts: 519
Nickname: charles
Registered: Feb, 2002
|
|
Re: adding action listioner to user defined component
|
Posted: Jun 19, 2002 12:39 PM
|
|
Note to the administrator: The java tags would not preserve the indents in this file. Some people get flamed over tiddly things like that. Please don't flame me. I don't care either way. I know how to use my text processor.
/* ClickRectangle.java * @author: Charles Bell * @version: June 19, 2002 */
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*;
public class ClickRectangle extends JApplet{ private boolean inAnApplet = true; private boolean debug = true;
public ClickRectangle(){ init(); } public static void main(String[] args){ ClickRectangle clicker = new ClickRectangle(); clicker.inAnApplet = false; clicker.init();
} public void init(){ getContentPane().add(new MyCanvas()); if (!inAnApplet){ JFrame frame = new JFrame("ClickRectangle"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(this); frame.pack(); frame.show(); }
} class MyCanvas extends Canvas implements MouseListener, MouseMotionListener{
private boolean isOnPad = false; private Rectangle rectangle = new Rectangle(50,50,50,50); public MyCanvas(){ setSize(Toolkit.getDefaultToolkit().getScreenSize()); addMouseListener(this); addMouseMotionListener(this); }
public void paint(Graphics g){ Graphics2D g2d = (Graphics2D)g; g2d.draw(rectangle); } /** Invoked when the mouse button has been clicked (pressed and released) on the Sketch Pad. */ public void mouseClicked(MouseEvent me){ if (debug) System.out.println("mouseClicked"); }
/** Invoked when the mouse enters the Sketch Pad. */ public void mouseEntered(MouseEvent me){ if (debug) System.out.println("mouseEntered"); isOnPad = true; }
/** Invoked when the mouse exits a componentthe Sketch Pad. */ public void mouseExited(MouseEvent me){ if (debug) System.out.println("mouseExited"); isOnPad = false; }
/** Invoked when a mouse button has been pressed on the Sketch Pad. */ public void mousePressed(MouseEvent me){ if (debug) System.out.println("mousePressed at " + me.getPoint().toString()); if (isInRectangle(me.getPoint())){ if (debug) System.out.println("rectangle was clicked"); } }
/** Invoked when a mouse button has been released on the Sketch Pad. */ public void mouseReleased(MouseEvent me){ if (debug) System.out.println("mouseReleased at " + me.getPoint().toString()); } /** Invoked when a mouse button is pressed on on the Sketch Pad and then dragged */ public void mouseDragged(MouseEvent me){ if (debug) System.out.println("mouseDragged"); }
/** Invoked when the mouse button has been moved onthe Sketch Pad (with no buttons down). */ public void mouseMoved(MouseEvent me){ if (debug) System.out.println("mouseMoved"); } private boolean isInRectangle(Point p){ return rectangle.contains(p); } } }
|
|