0

如何读取 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);
4

1 回答 1

2

这是一个古老的话题,但是,我将分享我的想法。

我相信您不需要像这样编写以下代码来获得价值。(使用 if 语句)

if (!source.getValueIsAdjusting()) {
          int sleepSense = (int)source.getValue();

你可以很好地满足以下条件

JSlider mySlider= new JSlider();
mySlider.addChangeListener(new ChangeListener(){
          public void stateChanged(ChangeEvent e) {
              int sleepSense = mySlider.getValue();
    }

那么您可以在程序中的任何位置使用值“sleepSense”。

于 2016-10-24T05:21:06.563 回答