我正在构建一个简单的程序,当用户的鼠标滚轮在滚动后停止时,我需要获取 boolean 值false
。我的代码如下,其中包含更多信息。
public class WheelHandler extends MouseAdapter {
public void mouseWheelMoved(MouseWheelEvent e) {
moved = e.getWheelRotation();
scrolling = true;
}
scrolling = false; // How do I make this run when the wheel becomes stopped?
}
最佳答案
滚动是一系列离散运动,因此您必须确定离散运动之间有多少时间意味着“停止”,然后使用 Swing 计时器来检查该时间增量。您需要决定某个任意时间片(下面是 int TIMER_DELAY = 100
或 100 毫秒),当用户移动鼠标滚轮时启动一些计时器,并在用户使用滚轮时取消相同的计时器在切片上升之前再次进行。
例如:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseWheelEvent;
import javax.swing.*;
@SuppressWarnings("serial")
public class NotifyWheelStopped extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private static final String WHEEL_STOPPED = "Wheel has stopped";
private static final String WHEEL_MOVING = "Wheel is moving";
public static final int TIMER_DELAY = 100;
private JLabel notificationLabel = new JLabel(WHEEL_STOPPED, SwingConstants.CENTER);
private WheelHandler wheelHandler = new WheelHandler();
private Timer wheelMovementTimer;
public NotifyWheelStopped() {
add(notificationLabel);
addMouseWheelListener(wheelHandler);
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class WheelHandler extends MouseAdapter {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
notificationLabel.setText(WHEEL_MOVING);
if (wheelMovementTimer != null && wheelMovementTimer.isRunning()) {
wheelMovementTimer.stop();
}
wheelMovementTimer = new Timer(TIMER_DELAY, new WheelMovementTimerActionListener());
wheelMovementTimer.setRepeats(false);
wheelMovementTimer.start();
}
}
private class WheelMovementTimerActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
notificationLabel.setText(WHEEL_STOPPED);
}
}
private static void createAndShowGui() {
NotifyWheelStopped mainPanel = new NotifyWheelStopped();
JFrame frame = new JFrame("NotifyWheelStopped");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
即使有 100 毫秒的延迟,当轮子缓慢转动时,通知也可能会跳动。
关于java - 检测鼠标滚轮停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32037282/