2017-03-19 22 views
-4
 public void mouseDragged(MouseEvent e) { 
     // TODO Auto-generated method stub 
     Rectangle rect = (Rectangle) e.getSource(); 
     if (isDragged) { 
      if (rect.contains(new Point(e.getX(), e.getY()))) { 
       r1.setBounds(e.getX(), e.getY(), 100, 100); 
       repaint(); 
       check(); 
      } 
     } 
    } 

如何處理Java GUI中的ClassCastException?我該如何處理Java GUI中的ClassCastException?

我想拖動我的矩形並選中碰撞。 當我拖動,產生一個錯誤代碼。 我想點擊矩形的地方來源並使用它來滿足條件並嘗試以下條件。

+0

什麼是'r1'? 「矩形」包含方法的定義是什麼? – nullpointer

+0

r1是矩形。 像這樣,Rectangle r1 = new Rectangle(10,10,50,50); 包含的定義 public boolean contains(Point p){ return contains(p.x,p.y); } –

回答

0

e.getSource()返回最初發生事件的組件。在mouseDragged()的情況下,它是接收鼠標按下事件的組件。該組件不能鑄造到Rectangle

表達new Point(e.getX(), e.getY())可以寫爲e.getPoint()