我正在用 Java 实现一个简单的水平 JSlider。没有刻度线或类似的东西。可能和人类想象的一样简单。
当我尝试通过用鼠标拖动 JSlider 左右“移动”它时,它的数值确实会更新(我设置了一个system.out
打印语句来报告滑块的变化值,它们看起来很好)。
但是,滑块旋钮本身不会移动。它只是停留在初始化期间开始的位置。关于这方面,“每个 JSlider 都应该拥有”某种样板代码吗?
我一直在玩“ChangeListener”的东西,但我一直在死胡同。
对我来说似乎工作正常,请发布SSCCE以显示具体问题:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SwingSliderExample extends JPanel {
public SwingSliderExample() {
super(true);
this.setLayout(new BorderLayout());
final JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
slider.setMinorTickSpacing(2);
slider.setMajorTickSpacing(10);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
// We'll just use the standard numeric labels for now...
slider.setLabelTable(slider.createStandardLabels(10));
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent ce) {
if (!slider.getValueIsAdjusting()) {//no adjustments are taking place thus we know the value is final
System.out.println(slider.getValue());
}
}
});
add(slider, BorderLayout.CENTER);
}
public static void main(String s[]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
JFrame frame = new JFrame("Slider Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SwingSliderExample());
frame.pack();
frame.setVisible(true);
}
});
}
}
参考: