基本上,您可以做的是在stateChanged
引发事件的时间和textField
更新的时间之间插入“强制延迟”。
这基本上意味着我们在stateChanged
尝试更新textField
.
因为我们不想阻塞事件调度线程,因为它会阻止处理任何新事件,所以我使用了javax.swing.Timer
.
基本上,每当stateChanged
调用该方法时,我都会重新启动计时器。一旦事件停止,计时器就可以完成并触发一个actionPerformed
事件,这使我们能够更新textField
...easy ;)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestSlider01 {
public static void main(String[] args) {
new TestSlider01();
}
public TestSlider01() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JSlider slider;
private JTextField textField;
private Timer slideTimer;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
textField = new JTextField(20);
slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 2);
slider.setFont(new Font("Dialog", Font.BOLD, 10));
slider.setMinorTickSpacing(1);
slider.setMajorTickSpacing(2);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
// textField.setText(String.valueOf(slider.getValue()));
slideTimer.restart();
}
});
slideTimer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textField.setText(String.valueOf(slider.getValue()));
}
});
slideTimer.setRepeats(false);
add(slider, gbc);
add(textField, gbc);
}
}
}
现在,我特意为延迟使用了一个较大的值,您不妨玩一下...
此外,setBounds
这是一个非常糟糕的主意。我会花时间学习布局管理器 API,从长远来看,它会为你省去很多心痛;)