2012-09-24 36 views
8

我一直在使用JSlider類有一些問題 - 特別是與刻度標籤。這是JSlider中的錯誤嗎?

我第一次使用setMajorTickSpacingsetMinorTickSpacing一切都按預期工作。但是,後續調用setMajorTickSpacing會更新刻度,但不更改標籤。我寫了一個簡單的例子來說明這種情況:

import java.awt.event.*; 
import javax.swing.*; 

public class SliderTest { 
    public static void main(String args[]) { 
     JFrame frame = new JFrame(); 
     frame.addWindowListener(new WindowAdapter() { 
      public void windowClosing(WindowEvent we) { 
       System.exit(0); 
      } 
     }); 
     frame.setSize(300, 250); 

     JSlider slider = new JSlider(0, 100, 0); 
     slider.setMajorTickSpacing(10); 
     slider.setMinorTickSpacing(1); 
     slider.setPaintLabels(true); 
     slider.setPaintTicks(true); 

     slider.setMajorTickSpacing(25); 
     slider.setMinorTickSpacing(5); 

     frame.add(slider); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
} 

兩個簡單的變通似乎來解決這個問題 - 無論是第二次調用setMajorTickSpacing之前使用slider.setLabelTable(null)slider.setLabelTable(slider.createStandardLabels(25))。鑑於此,標籤表似乎沒有被正確更新。

我不確定這是否是預期的行爲。我的第一本能是更新滴答間隔也應更新標籤,但也有分離兩者的論據。

所以我想知道它是什麼 - 這是JSlider中的錯誤還是預期的行爲?如果它是的預期行爲,那麼做出該選擇的突出理由是什麼?

+0

對我來說看起來像一個錯誤 - 好趕上:-) – kleopatra

+2

感謝您分享這個短暫的未來。 –

回答

5

您可以很容易地看到這個問題的原因,通過查看setMajorTickSpacing源代碼:

public void setMajorTickSpacing(int n) { 
    int oldValue = majorTickSpacing; 
    majorTickSpacing = n; 
    if (labelTable == null && getMajorTickSpacing() > 0 && getPaintLabels()) { 
     setLabelTable(createStandardLabels(getMajorTickSpacing())); 
    } 
    firePropertyChange("majorTickSpacing", oldValue, majorTickSpacing); 
    if (majorTickSpacing != oldValue && getPaintTicks()) { 
     repaint(); 
    } 
} 

如果兩次調用此方法 - labelTable值將不會爲空了,它不會被更新。它可能根據上述方法的評論是一個預期的行爲:

* This method will also set up a label table for you. 
* If there is not already a label table, and the major tick spacing is 
* {@code > 0}, and {@code getPaintLabels} returns 
* {@code true}, a standard label table will be generated (by calling 
* {@code createStandardLabels}) with labels at the major tick marks. 

所以,你必須你希望他們被更新(除非你重寫此方法與自己的,做了更新,每次手動更新標籤)。

+0

謝謝,當我看到源代碼時,我得出了同樣的結論。我仍然認爲文件可能會更好。 – charlemagne