这是代码:
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();
}
}
它应该在鼠标拖动时绘制圆圈,但事实并非如此。为什么呢?
答案 0 :(得分:3)
您必须添加鼠标侦听器。
public void init()
{
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
提示:尝试在IDE中使用 Ctrl - Shift - F 。通常,它会美化您的代码。 (Eclipse和NetBeans支持此功能)