java - 第一次鼠标拖动移动

标签 java swing

有没有办法计算出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

最佳答案

boolean first=true;//this should be a instance variable.

先拖!使用 boolean 变量来检测是否首先检测。就像这样

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
...............................

关于java - 第一次鼠标拖动移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29576840/

相关文章:

Java JFrame 卡住

java - 如何检查线程是否正在 hibernate ?

java - Filebeat 与直接从应用程序将日志推送到 Logstash

java - 错误 :Android Source Generator: [project] AndroidManifest. 找不到 xml 文件

java - 获取似乎从另一个类分层的内容

java - 如何制作JPanel的背景渐变

java - 如何使用 POI Apache 获取生成的 Excel 文件中列的大小或长度

java - 正则表达式问题 - 找到精确的变量

Java Swing : Mouseover text on JComboBox items?

java - 检查整个数组是否为instanceof