我正在尝试解决斯坦福 CS106A的橡皮筋问题。根据addMouseListener() 上的 Java Doc,需要一个侦听器才能使用它。根据这个问题的解决方案,没有使用监听器,但是当我在没有任何监听器的情况下使用它时,我收到以下错误:
Component 类型中的方法 addMouseListener(MouseListener) 不适用于 arguments()
如何创建一个侦听器以使其侦听整个画布?
/**
* This program allows users to create lines on the graphics canvas by clicking
* and dragging the mouse. The line is redrawn from the original point to the new
* end point, which makes it look as if it is connected with a rubber band.
*/
package Section_3;
import java.awt.Color;
import java.awt.event.MouseEvent;
import acm.graphics.GLine;
import acm.program.GraphicsProgram;
public class RubberBanding extends GraphicsProgram{
private static final long serialVersionUID = 406328537784842360L;
public static final int x = 20;
public static final int y = 30;
public static final int width = 100;
public static final int height = 100;
public static final Color color = Color.RED;
public void run(){
addMouseListener();
}
/** Called on mouse press to create a new line */
public void mousePressed(MouseEvent e) {
double x = e.getX();
double y = e.getY();
line = new GLine(x, y, x, y);
add(line);
}
/** Called on mouse drag to reset the endpoint */
public void mouseDragged(MouseEvent e) {
double x = e.getX();
double y = e.getY();
line.setEndPoint(x, y);
}
/* Private instance variables */
private GLine line;
}