0
我想寫一個GraphicsProgram,允許用戶在畫布上畫線。按下鼠標按鈕設置線的起點。隨着拖動的繼續,拖動鼠標移動另一個端點。釋放鼠標將行固定在當前位置,並準備開始新行。簡單的圖形交互
有人可以解釋爲什麼當我運行代碼行無法顯示,以及我也附加了正確的代碼,使得它更好。
我的代碼:`
import acm.program.*;
import java.awt.event.MouseEvent;
import acm.graphics.*;
public class DrawLines extends GraphicsProgram{
public void init(){
addMouseListeners();
line=new GLine(x1,y1,x2,y2);
}
public void mousePressed(MouseEvent e){
x1=e.getX();
y1=e.getY();
}
public void mouseDragged(MouseEvent e){
x2=e.getX();
y2=e.getY();
add(line);
}
private GLine line;
private int x1;
private int y1;
private int x2;
private int y2;
}
正確的代碼:
import acm.graphics.*;
import acm.program.*;
import java.awt.event.*;
/** This class allows users to drag lines on the canvas */
public class RubberBanding extends GraphicsProgram {
public void run() {
addMouseListeners();
}
/** 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;
}
GraphicsProgram類是否實現了可運行? –