Re: [問題] 設計移動多個圖案
※ 引述《ericsoneva (嗯~)》之銘言:
: 想要設計目前frame上有一些圖案
: 我可以點選frame的任何其中一個圖案移來移去(有點類似拼圖)
: 目前做法是利用
: public void mousePressed(MouseEvent e) {
: dx=e.getX()-posX; // 取得滑鼠按下之點與基準點x方向的距離
: dy=e.getY()-posY;
: }
: public void mouseDragged(MouseEvent e) {
: x=e.getX()-dx; // 取得拖曳時的基準點x座標
: y=e.getY()-dy; // 取得拖曳時的基準點y座標
: if(dx>0 && dx<100 && dy>0 && dy<120) // 如果指標落在正方形區域內
: {
: ttt1.setLocation(x,y);
: Graphics g = getGraphics();
: update(g);
: posX =x;
: posY =y;
: }
: }
: 滑鼠點下去後算基準點與滑鼠點的距離是否有落在圖案上
: 判斷為是點哪一張圖
: 但是這種方法常常會誤判 且圖一多整個會亂掉
: 而且圖如果重疊會被一起拉到
: if(dx>0 && dx<100 && dy>0 && dy<120) // 如果指標落在正方形區域內
: 且會因為圖的大小而要更改區域的大小
: 不知道有沒有好的方法可以用滑鼠去點選我想要移動的物件
: 謝謝
我前陣子有作一個case 是要做圓形的圖形點擊紀錄,
圖形的半徑跟位置都是隨機的。
我當時的作法是以JButton為底,修改paintComponent 畫出需要的圖形,
理由是套用 ActionListener 比較方便 XD
至於判斷有沒有在圓裡面,可以繼承原本的函式
contains 來寫自己的判斷式
以我當時圓形的例子
Shape shape=null;
public boolean contains(int x, int y) {
if (shape == null || !shape.getBounds().equals(getBounds())) {
shape = new Ellipse2D.Float(0 , 0 , r, r);
}
return shape.contains(x, y);
}
要注意這裡的x,y 是相對於該Conponent的x,y的數字
另外如果有重疊的情形,想要自己去控制誰上誰下,那就要另外再處理了..
總之,沒必要的話我不建議從座標出發,從Component出發會比較理想。
--
雖然早期沒搞懂 Component 時,我也都是從座標算。XD
--
I am a person, and I am always thinking .
Thinking in love , Thinking in life ,
Thinking in why , Thinking in worth.
I can't believe any of what ,
I am just thinking then thinking ,
but worst of all , most of mine is thinking not actioning...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.136.91.55
推
05/07 00:18, , 1F
05/07 00:18, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 3 篇):