作者TonyQ (沉默是金。)
看板java
标题Re: [问题] 设计移动多个图案
时间Thu May 6 19:07:57 2010
※ 引述《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
1F:推 ericsoneva:其实我看不太懂 不过谢谢你了 05/07 00:18