我的JFrame窗口具有系统外观和感觉,当我添加JSlider并单击其行时,它向前或向后移动90步,具体取决于我的鼠标位置。我希望钻石在我的鼠标下面工作,好像我点击并拖动钻石一样。
这是一个最小的程序,但我认为这只发生在Windows中,因为在默认的外观和感觉上,它没有捕捉到第90个数字,但仅前进了一个数字。
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
@SuppressWarnings("serial")
public class Test extends JFrame {
int value = 300;
JSlider slider;
JLabel label;
public Test() {
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
label = new JLabel(String.valueOf(value));
slider = new JSlider();
slider.setMinimum(100);
slider.setMaximum(1000);
slider.setValue(value);
slider.setSnapToTicks(false);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
label.setText(String.valueOf(slider.getValue()));
}
});
add(label, BorderLayout.NORTH);
add(slider);
setVisible(true);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new Test();
}
}
答案 0 :(得分:0)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class SliderMousePressed extends JPanel
{
public SliderMousePressed()
{
JSlider slider = new JSlider(0, 50, 20);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
add(slider);
snapToMouseClick( slider );
}
public static void snapToMouseClick(final JSlider slider)
{
MouseListener[] ml = slider.getMouseListeners();
for (MouseListener l : ml)
slider.removeMouseListener(l);
MouseMotionListener[] mml = slider.getMouseMotionListeners();
for (MouseMotionListener l : mml)
slider.removeMouseMotionListener(l);
final BasicSliderUI ui = (BasicSliderUI)slider.getUI();
BasicSliderUI.TrackListener tl = ui.new TrackListener()
{
// Position slider at mouse
@Override
public void mouseClicked(MouseEvent e)
{
Point p = e.getPoint();
int value = ui.valueForXPosition(p.x);
slider.setValue(value);
}
// Prevent scrolling while mouse button is held down
@Override
public boolean shouldScroll(int dir)
{
return false;
}
};
slider.addMouseListener(tl);
slider.addMouseMotionListener(tl);
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SliderMousePressed");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SliderMousePressed() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
此示例基于此answer,稍加修改以删除/添加MouseMotionListener以及MouseListener,以使拇指滑块的绘制与默认行为更加一致。现在,当拖动拇指时,拇指将绘制在与鼠标相同的相对位置,而不是在左侧。