Java applet doesn't draw on mouse events
this is the code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.Vector;
public class PainterNN extends Applet implements MouseListener, MouseMotionListener{
class MyShape{
int mx;
int my;
Color mc;
MyShape(int x, int y, Color c){
mx=x;
my=y;
mc=c;
}
void Render(Graphics g){
g.setColor(mc);
g.fillOval (mx,my,10,10);
}
}
Vector<MyShape> vec = new Vector();
public void init() {
}
public void paint(Graphics g) {
for(int i =0; i < vec.size() ; i=i+1){
MyShape s = vec.elementAt(i);
s.Render(g);
}
}
public void mouseEntered( MouseEvent e ) {
// called when the pointer enters the applet's rectangular area
}
public void mouseExited( MouseEvent e ) {
// called when the pointer leaves the applet's rectangular area
}
public void mouseClicked( MouseEvent e ) {
// called after a press and release of a mouse button
// with no motion in between
// (If the user presses, drags, and then releases, there will be
// no click event generated.)
}
public void mousePressed( MouseEvent e ) { // called after a button is pressed down
repaint();
// "Consume" the event so 开发者_如何学运维it won't be processed in the
// default manner by the source which generated it.
e.consume();
}
public void mouseReleased( MouseEvent e ) { // called after a button is released
repaint();
e.consume();
}
public void mouseMoved( MouseEvent e ) { // called during motion when no buttons are down
e.consume();
}
public void mouseDragged( MouseEvent e ) { // called during motion with buttons down
int mx = e.getX();
int my = e.getY();
vec.add(new MyShape(mx,my,new Color(0,255,0)));
repaint();
e.consume();
}
}
It should draw circles at mouse drag but it didn't. Why?
You have to add the mouse listeners.
public void init()
{
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
Hint: Try using Ctrl - Shift - F in your IDE. Normally, it will beautify your code. (Eclipse and NetBeans support this)
精彩评论