Have a look at code!!
I want to draw a rectangle in an applet and trace
the mouse pressed action only inside that rectangle
To achive this i have created 2 classes
1.Class Rect
This class extends Component and used to draw the Rectangle
using drawRect() method and used to trace the action performed
in side the Rect using a Thread
2.Class Display extends applet,implements ActionListener
and adds the textarea and the Rect class
this class is used to display the rectangle in the applet.
ActionListener is added to this class to trace any
action performed in the Rectangle.So when ever mouse key is
pressed in side the rectangle action event is generated and
that is appended into the textarea
My problem
Action event is fired in the entire area of the applet
how to get the action event(the mouse key press)only in side
the rectangle
I am drawing images dynamicaly at run time , i want to make the code
simplified,so i draw the rect in a class which extends the
component(actually i want to make the rect as a component like
button or label ) so that the addActionListener can be implemented
in that rect to trace any action
what i am doing is right ?
Here is the Runnable code
//////**class Rect***//////////////////////////
import java.awt.*;
import java.awt.event.*;
public class Rect extends Component implements Runnable,MouseListener
{
public Rect(){
addMouseListener (this);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillRect(10,10,30,30);
}
public synchronized void mousePressed (MouseEvent me) {
processAction ();}
public synchronized void mouseDragged (MouseEvent me) {}
public synchronized void mouseClicked (MouseEvent me) {}
public synchronized void mouseReleased (MouseEvent me) {}
public synchronized void mouseEntered (MouseEvent event){}
public synchronized void mouseExited(MouseEvent event){}
private ActionListener actionListener = null;
public synchronized void addActionListener (ActionListener al) {
actionListener = AWTEventMulticaster.add (actionListener, al);
}
public synchronized void removeActionListener (ActionListener al) {
actionListener = AWTEventMulticaster.remove (actionListener, al);
}
public void processAction () {
if (null != actionListener)
new Thread (this).start ();
}
public void run () {
try { actionListener.actionPerformed
(new ActionEvent(this,ActionEvent.ACTION_PERFORMED,toString ()));
} catch (Exception exc) {
System.out.println ("failed processAction:"+exc);
exc.printStackTrace ();
}
}
}
/////////////********Display***********/////////////////
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Display extends Applet implements ActionListener{
Rect1 rect;
TextArea textarea;
public Display(){
rect = new Rect1();
setLayout(new BorderLayout());
add(rect,BorderLayout.CENTER);
rect.addActionListener(this);
add (textarea = new TextArea (12,60),BorderLayout.SOUTH);
}
public void actionPerformed (ActionEvent evt) {
textarea.append ("\n"+evt);
}
}

