gpt4 book ai didi

java - Java中单击和双击的区别

转载 作者:搜寻专家 更新时间:2023-10-30 21:23:39 24 4
gpt4 key购买 nike

我搜索论坛并看到这段代码:

            public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
System.out.println(" and it's a double click!");
wasDoubleClick = true;
} else {
Integer timerinterval = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty(
"awt.multiClickInterval");
timer = new Timer(timerinterval.intValue(), new ActionListener() {

public void actionPerformed(ActionEvent evt) {
if (wasDoubleClick) {
wasDoubleClick = false; // reset flag
} else {
System.out.println(" and it's a simple click!");
}
}
});
timer.setRepeats(false);

timer.start();
}

}

但是代码运行不正确(有时它打印出“并且它是一次单击!” 2 次。它应该打印出“并且它是双击!”)。谁能告诉我为什么?或者你能给我一些更好的方法吗?谢谢!

最佳答案

Sometime it prints out " and it's a single click!" 2 times . It should print out " and it's a double click!").

这很正常。只有在指定的时间间隔内单击两次,才会发生双击。因此,有时如果您点击的速度不够快,您会连续点击两次。

Integer timerinterval = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval"); 

上面这行代码决定了双击的速度。

这里的值(value)是我用来做同样事情的一些代码。不知道它是否比您拥有的代码更好或更差:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class ClickListener extends MouseAdapter implements ActionListener
{
private final static int clickInterval = (Integer)Toolkit.getDefaultToolkit().
getDesktopProperty("awt.multiClickInterval");

MouseEvent lastEvent;
Timer timer;

public ClickListener()
{
this(clickInterval);
}

public ClickListener(int delay)
{
timer = new Timer( delay, this);
}

public void mouseClicked (MouseEvent e)
{
if (e.getClickCount() > 2) return;

lastEvent = e;

if (timer.isRunning())
{
timer.stop();
doubleClick( lastEvent );
}
else
{
timer.restart();
}
}

public void actionPerformed(ActionEvent e)
{
timer.stop();
singleClick( lastEvent );
}

public void singleClick(MouseEvent e) {}
public void doubleClick(MouseEvent e) {}

public static void main(String[] args)
{
JFrame frame = new JFrame( "Double Click Test" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.addMouseListener( new ClickListener()
{
public void singleClick(MouseEvent e)
{
System.out.println("single");
}

public void doubleClick(MouseEvent e)
{
System.out.println("double");
}
});
frame.setSize(200, 200);
frame.setVisible(true);
}
}

关于java - Java中单击和双击的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4577424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com