我有这段代码,但没有任何反应。我不知道为什么degreesSlider.getValue() + 1
不起作用。我会感谢任何建议。
degreesSlider.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
int notches = e.getWheelRotation();
if (notches < 0) {
System.out.println("Mouse wheel moved UP " + -notches + " notch(es)");
degreesSlider.setValue(degreesSlider.getValue() + 1);
} else {
System.out.println("Mouse wheel moved DOWN " + notches + " notch(es)");
degreesSlider.setValue(degreesSlider.getValue() - 1);
}
}
});
答案 0 :(得分:2)
尝试在How to Write a Mouse Wheel Listener上运行Swing教程中的代码。当我运行时,代码显示“缺口”仅在每3个单位的车轮运动中发生变化。因此,当您向上滚动时,实际上每次向上滚动都会获得3个向下滚动,并且滑块会缓慢向0移动。
作为一个快速解决方案,我刚刚做了:
if (notches < 0) {
System.out.println("Mouse wheel moved UP " + -notches + " notch(es)");
slider.setValue(slider.getValue() + 1);
} else
if (notches > 0) {
System.out.println("Mouse wheel moved DOWN " + notches + " notch(es)");
slider.setValue(slider.getValue() - 1);
}
答案 1 :(得分:2)
以下是使用鼠标滚轮旋转移动JSlider的代码Demo。我希望这可以帮助您更有效地处理JSlider的鼠标滚轮旋转。
import javax.swing.*;
import java.awt.event.*;
public class JSliderDemo extends JFrame implements MouseWheelListener
{
JSlider degreesSlider;
public void prepareAndShowGUI()
{
degreesSlider = new JSlider(0,100);
degreesSlider.setMajorTickSpacing(2);
degreesSlider.setMinorTickSpacing(1);
degreesSlider.setPaintLabels(true);
degreesSlider.setPaintTicks(true);
degreesSlider.setPaintTrack(true);
degreesSlider.addMouseWheelListener(this);
getContentPane().add(degreesSlider);
setSize(1000,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void mouseWheelMoved(MouseWheelEvent evt)
{
if (evt.getWheelRotation() < 0 )//mouse wheel was rotated up/away from the user
{
int iNewValue = degreesSlider.getValue() - degreesSlider.getMinorTickSpacing() ;
if (iNewValue >= degreesSlider.getMinimum())
{
degreesSlider.setValue(iNewValue);
}
else
{
degreesSlider.setValue(0);
}
}
else
{
int iNewValue = degreesSlider.getValue() + degreesSlider.getMinorTickSpacing() ;
if (iNewValue <= degreesSlider.getMaximum())
{
degreesSlider.setValue(iNewValue);
}
else
{
degreesSlider.setValue(degreesSlider.getMaximum());
}
}
}
public static void main(String[] st)
{
SwingUtilities.invokeLater( new Runnable()
{
@Override
public void run()
{
JSliderDemo jsd = new JSliderDemo();
jsd.prepareAndShowGUI();
}
});
}
}