我開發了一個繪製多邊形三角形的程序。三角形使用鼠標拖動繪製。三角形的座標存儲在數組列表中。每次鼠標光標,將鼠標懸停在現有繪製的三角形上(在三角形區域內),鼠標光標應該變成「CROSSHAIR_CURSOR」,但是這不會發生。幫助:-(鼠標移動-crosshair光標
...
public class DrawingBoardWithMatrix extends JFrame {
public static void main(String[] args) {
new DrawingBoardWithMatrix();
}
public DrawingBoardWithMatrix(){
this.add(new PaintSurface(), BorderLayout.CENTER);
...
}
private class PaintSurface extends JComponent {
java.util.List<Polygon> triangles = new LinkedList<Polygon>();
Point startDrag, endDrag, midPoint;
Polygon triangle;
public PaintSurface() {
...
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
startDrag = new Point(e.getX(), e.getY());
endDrag = startDrag;
repaint();
}//end mousePressed
public void mouseReleased(MouseEvent e) {
if (startDrag.x > endDrag.x)
midPoint = new Point((endDrag.x +(Math.abs(startDrag.x - endDrag.x)/2)),e.getY());
else
midPoint = new Point((endDrag.x -(Math.abs(startDrag.x - endDrag.x)/2)),e.getY());
int[] xs = { startDrag.x, endDrag.x, midPoint.x };
int[] ys = { startDrag.y, startDrag.y, midPoint.y };
triangles.add(new Polygon(xs, ys, 3));
startDrag = null;
endDrag = null;
repaint();
}//end mouseReleased
});//end addMouseListener
this.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
endDrag = new Point(e.getX(), e.getY());
repaint();
}//end mouseDragged
});//end this.addMouseMotionListener
}//end paintSurface
//THIS CODE DOESNT WORK - AND I AM STUCK :-(
public void mouseMoved(MouseEvent e) {
startDrag = new Point(e.getX(), e.getY());
if (triangles.contains(startDrag))
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
else
setCursor(Cursor.getDefaultCursor());
}// end mouseMoved
private void paintBackground(Graphics2D g2){
...
}
public void paint(Graphics g) {
...
}
}//end private class PaintSurface
}//end public class DrawingBoardMatrix
由於AKF 。我已經改變了addMouseMotionListener中mouseMoved方法的位置,但它仍然不起作用:-( – Jessy 2009-09-27 20:14:52
Jessy,我已經更新了我的答案,請看一下 – akf 2009-09-27 20:33:25
再次感謝akf。但是這聽起來很複雜,我會嘗試修改代碼 – Jessy 2009-09-27 21:18:13