我正试图解决Stanford CS106A的橡皮筋问题。根据{{3}},需要听众使用它。根据这个问题的解决方案,没有使用监听器,但是当我在没有任何监听器的情况下使用它时,我得到以下错误:
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;
}
答案 0 :(得分:1)
我试图在run()方法中添加addMouseListeners(),这就是问题所在。我上面的解决方案是添加一个GCanvas并听它也有效但不需要。应该使用init()而不是run()内部初始化addMouseListeners()。我以前无法使用init(),因为我正在学习使用自定义Karel.jar库引用的Stanfrod CS106A中的Java。这个库已经使init()方法最终,所以我无法在任何程序中引用它。在我删除了Karel.jar库并使用了来自jtf的acm.jar后,我能够使用init()并且能够直接使用addMouseListeners()到画布,而不在已绘制的画布上添加任何其他画布。 所以整个问题是Karel.jar!
答案 1 :(得分:0)
解决方案是添加一个GCanvas对象并在该对象上使用addMouseListener()。
GCanvas c = getGCanvas(); //Creates a GCanvas component so that addMouseListener could be applied to it.
c.addMouseListener(this); //Tracks mouse event for the canvas
然后我可以通过实现@madprogrammer所说的MouseInputListener来跟踪画布的鼠标事件。
答案 2 :(得分:0)
public class RubberBanding extends GraphicsProgram implements MouseListener {
public void run() {
GCanvas c = getGCanvas();
c.addMouseListener(this);
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseDragged(MouseEvent e) {}
}
您可以像我上面那样在类级别实现MouseListener。您还可以创建一个单独的具体类来实现它,并将其传递给画布而不是它。您甚至可以使字段变量等于实现侦听器的匿名类,并将其传递给Canvas对象。
MouseListener listener = new MouseListener() {
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseDragged(MouseEvent e) {}
}
class MyMouseListener implements MouseListener {
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseDragged(MouseEvent e) {}
}
public void run() {
GCanvas c = getGCanvas();
c.addMouseListener(listener);
// OR
GCanvas c = getGCanvas();
c.addMouseListener(new MyMouseListener());
}