如何读取 JSlider 的值?
我在我的程序中使用了滑块,这是我以前没有使用过的,但我正在努力显示对它所做的更改!
问题是,JLabel
当您打开程序 (50) 时会显示滑块的值,但是当您更改值时,标签不会。
这是代码:
设置滑块(在 setUpMenuItems 类中):
sensitivitySlider2 = new JSlider();//direction , min , max , current
sensitivitySlider2.setFont(new Font("Calibri",Font.BOLD,10));
sensitivitySlider2.setMajorTickSpacing(10);
sensitivitySlider2.setMinorTickSpacing(1);
sensitivitySlider2.setPaintLabels(true);
sensitivitySlider2.setPaintTicks(true);
sensitivitySlider2.setPaintTrack(true);
sensitivitySlider2.setAutoscrolls(true);
sensitivitySlider2.setBackground(Color.WHITE);
sensitivitySlider2.setBounds (15,200,250,100);
propertiesPanel.add(sensitivitySlider2);
建立监听器:
private void registerComponentsForEvents()
{
// Register all the JButton objects for action events
miniButton.addActionListener (this);
applyButton.addActionListener (this);
exitButton.addActionListener (this);
sensitivitySlider2.addChangeListener(this);
}
窗口侦听器和声明具体的方法:
void addWindowListener(Window w) {
w.addWindowListener(this);
}
//React to window events.
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
变更事件:
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
int sleepSense = (int)source.getValue();
}
}
然后这一行将 JLabel 设置为值:
sleepSense2 = String.valueOf(sleepSense);