2012-12-22 69 views
0

我正在Java中實現一個簡單的水平JSlider。沒有刻度線或任何類似的東西。可能和人類想象的一樣簡單。JSlider旋鈕不更新(基本Java)

當我嘗試「移動」的JSlider的通過鼠標拖動左右,其數值確實更新(我成立了一個system.out打印語句報告滑塊的變化值,它們看起來不錯) 。

但是,滑塊旋鈕本身不動。它只是停留在初始化期間開始的地方。在這方面有沒有某種「每個JSlider應該有的」樣板代碼?

我一直在玩「ChangeListener」的東西,但我一直在死路一條。

+1

您可以發佈您用來初始化JSlider的代碼嗎? –

回答

2

看起來工作得很好,我,請發表SSCCE顯示具體的問題:

enter image description here

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); 
      } 
     }); 
    } 
} 

參考: