在我的 Java 应用程序中,我有几个 JSlider,它们覆盖的范围非常广,例如 -16384 到 + 32767。拖动旋钮时的分辨率类似于 250。如果我选择旋钮,我可以将其增加 +/- 1方向键,但速度慢得离谱。我想我已经见过一些实现(不一定是 Java Swing),您可以按住一个键,然后旋钮滑块增量会小得多。我正在寻找一个实际的例子或一些关于如何去做的建议。
到目前为止,我所做的就是阅读此处的文档:
https://docs.oracle.com/javase/tutorial/uiswing/components/slider.html
TIA,
DL
有几种可能的方法,比如设置
JSlider#setSnapToTicks(true); JSlider#setMajorTickSpacing()
或者在按下的键上执行 negative/positiveBlockIncrement
操作而不是 negative/positiveUnitIncrement
操作。
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public final class SliderUnitIncrementTest {
private Component makeUI() {
JSlider slider0 = new JSlider(-16384, 32767);
slider0.setSnapToTicks(true);
// slider0.setMinorTickSpacing(0);
slider0.setMajorTickSpacing(1638);
JSlider slider1 = new JSlider(-16384, 32767);
InputMap im = slider1.getInputMap();
// negativeBlockIncrement PAGE_DOWN, ctrl PAGE_DOWN
// positiveBlockIncrement PAGE_UP, ctrl PAGE_UP
KeyStroke ks1 = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
im.put(ks1, "negativeBlockIncrement");
KeyStroke ks2 = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
im.put(ks2, "positiveBlockIncrement");
// negativeUnitIncrement LEFT, KP_LEFT, DOWN, KP_DOWN
// positiveUnitIncrement RIGHT, KP_RIGHT, UP, KP_UP
KeyStroke ks3 = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.CTRL_DOWN_MASK);
im.put(ks3, "negativeUnitIncrement");
KeyStroke ks4 = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.CTRL_DOWN_MASK);
im.put(ks4, "positiveUnitIncrement");
JPanel p = new JPanel(new GridLayout(2, 1, 64, 64));
p.add(slider0);
p.add(slider1);
JPanel panel = new JPanel(new BorderLayout());
panel.add(p, BorderLayout.NORTH);
panel.setBorder(BorderFactory.createEmptyBorder(32, 64, 0, 64));
return panel;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new SliderUnitIncrementTest().makeUI());
frame.setSize(320, 240);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}