这是使用鼠标滚轮旋转移动 JSlider 的代码演示。我希望这可以帮助您更有效地处理 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();
}
});
}
}