我正在构建一个简单的程序,当用户的鼠标滚轮在滚动后停止时,我需要获得布尔值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?
}
答案 0 :(得分:1)
滚动是一系列离散运动,因此您必须决定离散运动之间的时间意味着“停止”,然后使用Swing Timer检查此时间增量。您将需要决定某个任意时间片(低于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毫秒,当车轮缓慢转动时,通知也会跳动。