2011-07-11 33 views
-2

这是代码:Java小程序没有鼠标事件绘制

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(); 
    } 


} 

应该在拖动鼠标绘制圆,但事实并非如此。为什么?

回答

3

您必须添加鼠标侦听器。

public void init() 
{ 
    this.addMouseListener(this); 
    this.addMouseMotionListener(this); 
} 

提示:尝试使用按Ctrl - 在你的IDE ˚F - 。通常,它会美化你的代码。 (Eclipse和NetBeans支持这个)

+0

该类实现'MouseListener'。 – mre

+2

@little:这还不够。 –

+0

+1,哎呀,我的坏.. :) – mre