有没有办法找出Java中鼠标的第一次拖动?
例如:
public void mouseDragged(MouseEvent e)
{
if (first drag of the mouse) // what should I write here?
System.out.println("This is the first drag");
else System.out.println("This isn't the first drag");
}
如果我拖动鼠标5次,我应该在控制台中看到这个文字:
This is the first drag
This isn't the first drag
This isn't the first drag
This isn't the first drag
This isn't the first drag
答案 0 :(得分:1)
boolean first=true;//this should be a instance variable.
先拖动!使用布尔变量首先检测或不检测。比如
public void mouseDragged(MouseEvent e)
{
if (first) { // this is only true if it's first drag
System.out.println("This is the first drag");
first=false;
}
else {
System.out.println("This isn't the first drag");
}
}
...更新
这是你可以检测到的第一次拖动。但是拖动时通常会触发鼠标拖动事件的问题。为了避免这种情况你可以修改这一点。
声明实例变量
boolean draging = true;
boolean mark = true;
boolean first = true;
仅在拖动开始时打印。当我们打印鼠标拖动时,我们停止打印它,直到鼠标释放并进行重新整理。
public void mouseDragged(java.awt.event.MouseEvent evt) {
draging = true;
if (mark) {
if (first) {
System.out.println("This is the first drag");
}else{
System.out.println("This isn't the first drag");
}
mark = false;
}
}
首先更改为false,因此首先拖动就足够了。并准备好打印新拖动[mark = true]
public void mouseReleased(java.awt.event.MouseEvent evt) {
if (draging) {
mark = true;
first=false;
}
}
这是第一个和更新的例子的输出。第一个代码存在问题[因为在拖动时连续触发事件拖动,而不是一个]。
第一个例子
This is the first drag
This is the first drag
This is the first drag
.............................//this continues until u finish[released] first drag
This isn't the first drag
This isn't the first drag
This isn't the first drag
................................
更新了一个
This is the first drag //a drag [ click--move--relesed] mark only 1time
This isn't the first drag
This isn't the first drag
This isn't the first drag
...............................
答案 1 :(得分:0)
我会稍微修改FastSnails解决方案以解决当按钮关闭时mouseDragged在每个鼠标移动时触发的行为:
boolean first = true;
boolean triggered = false;
public void mouseDragged(MouseEvent e){
if(!triggered){
if(first){
System.out.println("This is the first drag");
first=false;
}
else{
System.out.println("This isn't the first drag");
}
triggered = true;
}
}
当然,我们必须在mouseReleased事件中重置该标志,这标志着“拖动”的结束:
public void mouseReleased(MouseEvent e){
triggered = false;
}
使用此方法意味着每次“拖动”只会触发一次消息,而不是每次鼠标移动都会触发。