Dynamic JSlider tick spacing

I run several times into the situation where I needed to hardcode a JSlider tick spacing into my program. I always found it difficult to define the tick spacing because a good looking tick spacing depends on the current size of the JSlider on screen and its maximum value.
For my purposes I created a short function that automatically sets a "good looking" tick spacing (labels do not cover more than half of the slider width and use familiar spacing values like 1,2,5,10,20,50,...).
I wanted to share this little piece of code with you, maybe it helps someone...
Here it is:
    private void setMajorTickSpacing(JSlider slider, int maxValue) {
        Graphics graphics = slider.getGraphics();
        FontMetrics fontMetrics = graphics.getFontMetrics();
        int width = slider.getWidth();
        // try with the following values:
        // 1,2,5,10,20,50,100,200,500,...
        int tickSpacing = 1;
        for (int i = 0, tmpWidthSum = width + 1; tmpWidthSum > (width / 2);
                i++) {
            tickSpacing = (int) Math.pow(10, (i / 3));
            switch (i % 3) {
                case 1:
                    tickSpacing *= 2;
                    break;
                case 2:
                    tickSpacing *= 5;
            tmpWidthSum = 0;
            for (int j = 0; j < maxValue; j += tickSpacing) {
                Rectangle2D stringBounds = fontMetrics.getStringBounds(
                        String.valueOf(j), graphics);
                tmpWidthSum += (int) stringBounds.getWidth();
                if (tmpWidthSum > (width / 2)) {
                    // the labels are longer than the slider
                    break;
        slider.setMajorTickSpacing(tickSpacing);
        slider.setLabelTable(createLabels(slider, tickSpacing));
    }To have your tick spacing dynamically adopted when the user resizes the window, you should use a code snippet similar to the following one:
        jSlider.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                setMajorTickSpacing(jSlider, maxValue);
        });There is still room for improvement, like handling minimum values etc.
Feel free to improve the code. And please share it with us! :-)

OK, I added some dukes. They will be spend on code improvements. ;-)

Similar Messages

  • Tick spacing on a gauge control

    I am using a gauge control to make a tachometer indicator.  The tick spacing that I get on the gauge is quite a bit finer than I would like (too many ticks).  Does anyone know how to adjust the tick spacing on the control?  I want a scale that ranges from 0 to 6 with a total of 7 ticks (0, 1, 2, 3, 4, 5, 6).

    Hi cbfsystems,
    you can use the scale function of this control. With this function it is possible to set user defined points. right click the control and select axis arrangement, select user-defined. After that you can insert subdivisions.
    Mike
    Message Edited by MikeS81 on 03-31-2008 04:57 PM
    Attachments:
    Unbenannt 6_LV80.vi ‏6 KB

  • Dynamic Text line spacing issue

    Hi, in my Flash movie (CS3) I want all text to be selectable.
    When I select 'static' and 'selectable', I have the following issues:
    - Some of the text does not fit into the available (scrolling required to see the end of text)
    - This is larger than when in Flash.
    When I use 'dynamic' text, I have the following issues:
    - The line spacing displays different in the exported swf than it does in Flash (line spacing is much greater in the swf)
    - I am a designer so the appearance / positioning of the text is crucial
    Is this common?
    Is there any way to make the text in Flash and swf appear consistent?
    Many thanks

    First of all, maybe you don't know it, but static text can't be made selectable even in theory. Therefore what you're seeing when you click "Selectable" option, is a dynamic text. As for line spacing, I don't see any difference between Flash CS4 and resulting SWF. The only strange thing I've found is the necessarity to enlarge the bounding rectangle when I change the text type from static to dynamic. Otherwise bottom line of text just disappears. It looks like a bug. Also I don't see "Autosize" option being working here in CS4. I doubleclick on bottom right corner of the text block, small square is transformed into a diamond, and bounding rect is "autosized" around the text block. But the bottom text line disappears just as I deselect the text object. All it looks some stange...

  • JSlider tick / movement

    here's the problem :
    1> i want to create a JSlider with specific MajorTick like for a Slider 1->100 , 15-35-42-80
    so i can't use setMajorTickSpacing()
    2>i also want to have a button" previous" and a button "next" , in order to move the slider
    thx

    1> i want to create a JSlider with specific MajorTick
    like for a Slider 1->100 , 15-35-42-80
    so i can't use setMajorTickSpacing()this might be a bit of a workaround
    import javax.swing.*;
    import java.awt.*;
    class JSliderLabels extends JFrame
      public JSliderLabels()
        setLocation(400,200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JSlider slider = new JSlider(1,100,1);
        slider.setMajorTickSpacing(10);
        slider.setPaintTicks(true);
        java.util.Hashtable labelTable = new java.util.Hashtable();
        UIManager.put("Label.font",new Font("Ariel",Font.PLAIN,8));
        labelTable.put(new Integer(15),new JLabel("15"));
        labelTable.put(new Integer(35),new JLabel("35"));
        labelTable.put(new Integer(42),new JLabel("42"));
        labelTable.put(new Integer(80),new JLabel("80"));
        slider.setLabelTable(labelTable);
        slider.setPaintLabels(true);
        JPanel jp = new JPanel();
        jp.add(slider);
        getContentPane().add(jp);
        pack();
      public static void main(String[] args){new JSliderLabels().setVisible(true);}
    2>i also want to have a button" previous" and a
    button "next" , in order to move the slideradd your buttons, addActionListeners with slider.setValue([whatever])

  • Need help setting the exact size of my JSlider

    Hello everyone. I'm trying to build a small program to help people learn a about RGB colour values, and at the same time teach myself a bit more about Java. Things have been going fine so far until I came to setting my JSlider's size. The intention is to have three JSliders with a JPanel next to each. The I need the track of the slider to be exactly 256 pixels tall (one pixel per gradient value painted into the adjacent JPanel) plus whatever extra padding and spacing the Look And Feel dictates.
    I've got the height set to 256 pixels in the following code, but it makes the JSlider as a whole 256 pixels tall and so squishes the track. I've set the minor tick spacing to 2 so that if the track was actually 256 pixels tall, the ticks would alternate over each screen pixel. If you compile and run the code, you will notice that a few ticks appear next to each other without a one-pixel gap between them. I've also verified it by taking a screen capture, pasting it into the GIMP and then using the measure tool to check the size.
    I've tried searching through the API documentation to find ways of doing it, or to see if some ideas I've had so far were possible, but so far, I've not found anything particulairly satisfactory. I even tried to see if I could set the JSlider size to current JSlider size minus the track size, plus 256, but I couldn't find a way of getting the current size of the track.
    Can anyone help me out here? I'm rather stuck.

    Here's the code with all but the JSliders stripped out. Sorry about having to put it in a seperate post; the forum wouldn't allow it.
    Here's the code I have so far:
    package com.stephenphilbin.colourcoder;
    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.GroupLayout;
    import javax.swing.GroupLayout.Alignment;
    import javax.swing.GroupLayout.ParallelGroup;
    import javax.swing.GroupLayout.SequentialGroup;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSlider;
    import javax.swing.UIManager;
    import javax.swing.border.LineBorder;
    import javax.swing.border.TitledBorder;
    public class Colourcoder extends JFrame {
        private void initComponents() {
            String colourcoderTitle = "Colourcoder";
            String lightsPanelBorderText = "Lights";
            // Create the lights panel, set the borders and set up layout references
            JPanel lightsPanel = new JPanel();
            TitledBorder lightsPanelBorder = new TitledBorder(LineBorder.createGrayLineBorder(), lightsPanelBorderText);
            lightsPanel.setBorder(lightsPanelBorder);
            GroupLayout lightsPanelLayout = new GroupLayout(lightsPanel);
            lightsPanel.setLayout(lightsPanelLayout);
            // Initialize each light slider
            JSlider[] lightSliders = new JSlider[3];
            for (int i = 0; i < lightSliders.length; i++) {
                lightSliders[i] = new JSlider(JSlider.VERTICAL, 0, 255, 0);
                lightSliders.setPaintTrack(false);
    lightSliders[i].setMajorTickSpacing(16);
    lightSliders[i].setMinorTickSpacing(2);
    lightSliders[i].setPaintTicks(true);
    lightSliders[i].setSnapToTicks(true);
    // Loop through the light sliders and add them to the lights panel
    SequentialGroup horizontalLightGroup = lightsPanelLayout.createSequentialGroup();
    for (int i = 0; i < lightSliders.length; i++) {
    horizontalLightGroup.addGroup(lightsPanelLayout.createParallelGroup().addComponent(lightSliders[i]));
    SequentialGroup verticalLightGroup = lightsPanelLayout.createSequentialGroup();
    ParallelGroup parallelLightsGroup = lightsPanelLayout.createParallelGroup();
    verticalLightGroup.addGroup(parallelLightsGroup);
    for(int i = 0; i < lightSliders.length; i++) {
    parallelLightsGroup.addComponent(lightSliders[i], 256, 256, 256);
    lightsPanelLayout.setHorizontalGroup(horizontalLightGroup);
    lightsPanelLayout.setVerticalGroup(verticalLightGroup);
    // Final window/frame configuration
    setTitle(colourcoderTitle);
    setResizable(false);
    setLocationRelativeTo(null);
    GroupLayout frameLayout = new GroupLayout(getContentPane());
    getContentPane().setLayout(frameLayout);
    frameLayout.setAutoCreateContainerGaps(true);
    frameLayout.setHorizontalGroup(
    frameLayout.createParallelGroup(Alignment.LEADING)
    .addGroup(
    frameLayout.createSequentialGroup()
    .addComponent(lightsPanel))
    frameLayout.setVerticalGroup(
    frameLayout.createParallelGroup(Alignment.LEADING)
    .addGroup(
    frameLayout.createSequentialGroup()
    .addComponent(lightsPanel))
    pack();
    public Colourcoder() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    UIManager.put("swing.boldMetal", Boolean.FALSE);
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
    System.exit(1);
    initComponents();
    * @param args the command line arguments
    public static void main(String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Colourcoder().setVisible(true);
    Edited by: S_Philbin on Sep 29, 2008 11:18 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Knob problems

    Here are list of steps which result in my  problem, which occurs programatically as well as in the vc++ resource editor.
    1) Create a top gauge  meter with a range of 0 to 10.
    2) Add a pointer that is invisible, set the fill colour to blue and fill value to less than 3
    3) Add a pointer that is invisible, set the fill colour to green  and fill value to less than 6
    4) Add a pointer that is invisible, set the fill colour to red and fill value to less than 10
    note the orig pointrer should be set to visible with no fill style
    Now siwtch style to 'dial' all the fill info is lost and needles become visible, -is this a known bug?
    Also when Iam using a knob control how do Programatically turn off the numeric labels on the scale but keep the ticks, it cna be done easily with vc++ resource editor.
    I thought there would be a setvisible method in CNiLabels, but that is not the case
    Also having a problem with the NINumedit component when comes to redrawing its 3D border, seems to loose it after it gets focus. The component  then becomes flat style component.
    If i force a redraw by resizing  the formview it sits on it regains its style.
    My version of mstudio is 7.1.0.306.
    Cheers,
    Paul

    Hi,
      With regards to the pointers on the CWKnob control, this was reported to R&D (# CAR 44A4POW3) for further investigation.
    R&D is currently investigating this issue.
    As far as making the labels dissappear, you can do this using ValuePairs (for every major tick, you need to put in a value pair) :
    // Specify the axis range and tick spacing for the CWSlide control.
    m_knob_control.Axis.Maximum = 10;
    m_knob_control.Axis.Minimum = 0;
    // Set divisions to zero to display control without ticks and labels.
    m_knob_control.Axis.Ticks.MajorDivisions = 0;
    m_knob_control.Axis.Ticks.MinorDivisions = 0;
    // Add a value pair to indicate the low end of the axis value range on the CWSlide control.
    CNiValuePair vpair = m_knob_control.Axis.ValuePairs.Add();
    // Specify the value pair text.
    vpair.Name = "0";
    // Specify the axis value with which to associate the value pair.
    vpair.Value = 0;
    // Add a value pair to indicate a point along the axis value range on the CWSlide control.
    CNiValuePair vpair2 = m_knob_control.Axis.ValuePairs.Add();
    // Specify the value pair text.
    vpair2.Name = "5";
    // Specify the axis value with which to associate the value pair.
    vpair2.Value = 5;
    // Add a value pair to indicate the high end of the axis value range on the CWSlide control.
    CNiValuePair vpair3 = m_knob_control.Axis.ValuePairs.Add();
    // Specify the value pair text.
    vpair3.Name = "10";
    // Specify the axis value with which to associate the value pair.
    vpair3.Value = 10;
    // Specify that the value pairs are associated with the axis values and that the labels are visible.
    m_knob_control.Axis.ValuePairs.Location = CNiValuePairs::LocationValue;
    // decide if we're showing the labels or not (so Value here is just a boolean flag I was using - obviously you don't need this if you're setting it permanently off)
    if (Value)
       m_knob_control.Axis.ValuePairs.LabelType = CNiValuePairs::LabelNone;
    else
       m_knob_control.Axis.ValuePairs.LabelType = CNiValuePairs::LabelName;
    The third issue of the NiNumEdit dropping it's 3D style border when re-drawing - do you have a small project to demonstrate this?
    Thanks
    Sacha Emery
    National Instruments (UK)
    // it takes almost no time to rate an answer

  • Can we zoom and use value pairs for the axis?

    Hi!
    I am utilizing visual C++ 6.0 and Component works for my current project where we are displaying some electrical faults on the CWGraph class in log scale. The X Axis is in duration format, i.e. ms, sec, min, day etc. and I am utilizing value pairs to properly display the labels values in the X axis. I set the major and minor unit interval values to zero and added value pairs for the X axis values 1 ms, 10ms, 100 ms ...1 day, etc. ( I looked at the answers to the previously posted questions for this!!). Hence I can show the values in log scale for the x axis succesfully. However, after adding the value paires, the two axis zoom option, track mode = ZoomrectXY doesnot work and I cannot zoom when I display the graph. If t
    he value pairs are removed and use normal scaling, the zooming comes back. Is there a workaround to this problem.
    I would greatly appreciate your help!!
    Asaf

    Bilal,
    Since I am using my custom x axis labels as value pairs, I need to check the auto-scaling false, otherwise the log values for the x axis and value pair labels mix and do not look good on the graph. Below are the settings I used for graph:
    Axes->X Axis->Scale Style->Auto Scale: Unchecked
    Axes->X Axis->Scale Style->Minimum : 0
    Axes->X Axis->Scale Style->Maximum : 1e+009
    Axes->X Axis->Scale Style->Log : Checked
    Axes->X Axis->Scale Style->Inverted : Unchecked
    Axes->Y Axis->Scale Style->Auto Scale: Checked
    Axes->Y Axis->Scale Style->Log : Unchecked
    Axes->Y Axis->Scale Style->Inverted : Checked
    Ticks->X Axis->Tick Spacing->Major : 0
    Ticks->X Axis->Tick Spacing->Minor : 0
    Ticks->X Axis->Tick Spacing->Base : 0 ( All grayed out)
    Ticks
    ->Y Axis->Tick Spacing : Automatic
    The other settings are assigned default values.
    Hence, as I mentioned before the X Axis values are assigned as 1 sec, 10 sec, 1min, 10 min, 1 h ..etc.
    and all on log scale. I need to utilize value pairs for this I think. Since I do not want the auto scale values, I uncheck it. You mentioned by unchecking auto scale, one will not be able to zoom. If so, is there another approach to display the graph as I want and zoom at the same time?
    Thanks,
    Asaf

  • Essbase number of days calc

    We have a Time dimension which has the below member.
    NumDays
         Q3Days
               Oct (31)
               Nov (30)
               Dec (31)
    The values for Oct, Nov and Dec are hard coded as 31, 30, and 31 respectively. But I want them to return the actual number of days based on today's date. For example, if today is Oct 03 then Oct should return 2 days, Nov and Dec 0 days. And if today is Nov 05, Oct should return 31 days, Nov should return 04 days and Dec 0 days.
    Is there any calc or function that I can use to get the above result.
    Thanks.

    Got it, thanks.  In that case Celvin's solution (or one of the other sample date CDFs available here) will get you what you need.
    If you do have a batch process to attach to, you could look at updating the member formula dynamically, or having a static formula point to a specific intersection and then load the values to the cube, or update substitution variables referenced by a static formula...
    But if it really must be 100% dynamic and tick over at midnight without any process run, I think a CDF is your only option.

  • Duplicate Dial Chart Values

    Hey Everyone,
    This must be easy to solve, but my searches have yet to reveal the answer. I just created a simple chart based on the average value from a table. Here is my source query:
    SELECT AVG(TIME_VAL) VALUE, 5 MAX, MIN(TIME_VAL) LOW, MAX(TIME_VAL) HIGH FROM PROJECT_SURVEYS
    However, on the output chart I get values of 0,0,1,1,2,2,3,3,4,4,5,5. Why??
    Mike

    Hey,
    Not too sure what you mean here. The label is derived from the value (AVG(TIME_VAL)). I tried removing the labels, but I get exactly that - no labels.
    I just experimented with decimal places and it seems to work 'properly' now. I changed it to 2 decimal places and now my values show as:
    0.00
    0.50
    1.00
    1.50
    Shouldn't this have worked with 1 decimal place, which I tried, because it would be nice to only show the one?? Also, how could I go about removing the labels for these intermediate (0.50) ticks?? Any thoughts are appreciated,
    I just tried a 'tick spacing' of 1. This is nice for limiting the labels, intervals, but it would still be nice to be able to use 'intermediate' and unlabelled ticks. What I have now will suffice however,
    Mike
    Message was edited by:
    given2fly

  • Characteristic not required in RR

    Dear QM Gurus,
    In inspection plan i have 5 charateristic, after GRN all get copied in inspection lot, now clients requirement is to check only three of five. So how to remove those 2 characteristic from lot.
    thanks in advance
    kailash thakkar

    Hi
    following are the steps:
    1.Go to QDR1.
    2.Dynamic modification: Tick on At lot creation
    3.Press F5
    4.Now In stage enter 10,Click on Skip ,write short text as "Skip"
    5.select line & click on stage change.
    6.A new window will appear
    7.Number of skips:100
       New stge change:10
    Not ok
          New stge change:10
    8.save DMR
    Now Go to QP01
    Go to header level
    Enter Dynamic Modification level: Dynamic Modification at char Level
    Keep Modification blank
    Then go to Inspection char
    The char which you don't want to inspect maintain the DMR you have created.(only to those char)
    and save task list.
    Now when a lot is created go to result recording.
    The char which you don't want to inspect will be Gray.
    I hope you have understood.
    Regards
    Sujit

  • How to Align MC's evenly across an Arc

    Hello all,
            Does anyone know how I can align several circular MC's evenly across an arc. I want to be able to specify the number of circles along the arc and have them dynamically adjust their spacing.
        Sort of the way use can use "Replace Spline" in Illustratior when working with blends.
        Any help would be apprecited.
    Thanks
    Craig

    For example:
    drawCircles();
    function drawCircles():void
              var center:Point = new Point(300, 300);
              var radius:Number = 200;
              var numCircles:int = 10;
              var arcSegement:Number = Math.PI;
              var angle:Number = -Math.PI;
              var segment:Number = arcSegement / numCircles;
              var circleShape:Shape;
              while (numCircles--)
                        circleShape = circle;
                        addChild(circleShape);
                        circleShape.x = center.x + radius * Math.cos(angle);
                        circleShape.y = center.y + radius * Math.sin(angle);
                        angle += segment;
    function get circle():Shape
              var s:Shape = new Shape();
              s.graphics.beginFill(0xff0000);
              s.graphics.drawCircle(0, 0, 20);
              return s;

  • How to disable (grey-out) the ticks of a JSlider?

    Hi everyone,
    In my GUI, I have a JSlider that I want to be disabled (greyed out)
    because it should be only actived on my application next version.
    (It is important though to have it to preserve GUI appearence).
    Problem is that I was unable to greyout the ticks even though
    already managed to grey out the slider and the number labels.
    Right now, it is pretty uggly to have a partial disabled slider,
    because due to ticks not being disabled.
    Questions:
    1) Does anyone have an idea of how to do it?
    A small part of my code is shown below:
    JSlider dynSl = new JSlider();
    dynSl.setMajorTickSpacing(1);
    dynSl.setValue(0); //Default
    dynSl.setMaximum(7);
    dynSl.setMinimum(0);
    dynSl.setPaintLabels(true);
    dynSl.setPaintTicks(true);
    dynSl.setFont(new java.awt.Font("Dialog", 0, 9));
    dynSl.setSnapToTicks(true);
    dynSl.setEnabled(false);
    // small code just to put the numbers of the slider smaller
    Enumeration enum = dynSl.getLabelTable().elements();
    while (enum.hasMoreElements()) {
    JLabel elem = (JLabel)enum.nextElement();
    elem.setFont(new Font("Dialog",0,8));
    elem.setEnabled(false);
    2) If not possible, how do I change the colour of a JSlider (including
    the Ticks)?
    My idea is to change Slider's colour to the same grey colour one used
    to disable it, making at the end the slider look as if it was disabled.
    Thanks in advance,
    Jorge

    Hi again,
    Thanks for the help.
    I was trying to avoid not having the ticks at all but it seems to be
    the best choise because I could not solve the problem of greying out
    them.
    I did some more troubleshooting though and for my surprise, if I use
    the same code alone, i.e, a simple frame with just the slider it works
    fine. I even thought that it was related with having Windows LnF as
    opposed to Metal (Java) LnF, but that was not the problem.
    The only thing it comes to mind, is that there may be some problem by including the slider on a GridBagLayout !?!?!?
    Anyway,
    What has no simple solution, solved is! :-)
    Jorge

  • Auto scrolling dynamic text field(news ticker)

    > This message is in MIME format. Since your mail reader
    does not understand
    this format, some or all of this message may not be legible.
    --B_3272625483_2679871
    Content-type: text/plain;
    charset="US-ASCII"
    Content-transfer-encoding: 7bit
    Does anyone know how to make a scrollable dynamic text field
    scroll on its
    own and also with user interaction?
    Thanks in advance for your help.
    Bill
    --B_3272625483_2679871
    Content-type: text/html;
    charset="US-ASCII"
    Content-transfer-encoding: quoted-printable
    <HTML>
    <HEAD>
    <TITLE>Auto scrolling dynamic text field(news
    ticker)</TITLE>
    </HEAD>
    <BODY>
    <FONT FACE=3D"Verdana, Helvetica, Arial"><SPAN
    STYLE=3D'font-size:12.0px'>Does =
    anyone know how to make a scrollable dynamic text field
    scroll on its own an=
    d also with user interaction?<BR>
    <BR>
    Thanks in advance for your help.<BR>
    <BR>
    Bill</SPAN></FONT>
    </BODY>
    </HTML>
    --B_3272625483_2679871--

    I found this:
    http://www.kirupa.com/developer/mx/dynamic_scroller.htm
    I copied the actual scroller and put it in my .fla and it
    worked! Now if I can only figure out links in XML...

  • How to set the color of ticks in JSlider

    Hi,
    Question about JSlider.
    I am trying to set various colors between the ticks. However, I have gone thro' the javadoc of JSlider but find no such API.
    How could I go this?
    Thanks in advance for any inputs and ideas.
    Wing

    Here is quick demo about customize thumb.
    It is similar for customize other part of JSlider.
    You can use setUI to force use your own UI.
    Create your UI, the better way is extend from existing UI,
    for example: BasicSliderUI or MetalSliderUI (or... depend on L&F you want).
    Check the BasicSliderUI and MetalSliderUI API
    customize the paintXXXX method, that's it.
    Good Luck.
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.plaf.metal.MetalSliderUI;
    public class Test {
      public static void main(String[] args) {
        JFrame f = new JFrame();
        JSlider slider = new JSlider();
        slider.setPaintTicks(false);
        slider.setUI ( new MetalSliderUI() {
          public void paintThumb(Graphics g)  {
              Rectangle knobBounds = thumbRect;
              Color color = g.getColor();
              g.setColor(Color.red);
              g.fillOval(knobBounds.x, knobBounds.y, 15,15);
              g.setColor(color);
        f.getContentPane().add (slider);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

  • JSlider randomly missing tick labels

    Hello everyone,
    I am having a problem with JSliders. I have an application that has several JSliders throughout. They are vertical, min=100 and max=1000, with major ticks every 100, and minor ticks every 25, and the ticks and labels are painted.
    I have noticed that out of say 10 such sliders in my application, perhaps one or two sliders are randomly missing some ticks. For example, the labels will read 100, 200, 300, 400, 500, 600, 700, 900, 1000 (with the 800 just missing). The space for the text is there, but no text.
    As I mentioned, this doesn't always occur. It occurs perhaps on one or two sliders out of 10 every time I start the application. So this would seem to me to be related to a threading issue.
    Here is the constructor that creates the panel that has the JSlider in it:
           try{                                                                                                                                   
                SwingUtilities.invokeAndWait( new Runnable(){ public void run(){                                                                   
                    // INIT GUI & CUSTOM INIT                                                                                                      
                    initComponents();                                                                                                                                                                                                                          
                    depthJSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE);                                                              
            catch(Exception e){ Util.handleExceptionNoRestart("Error building Log Table", e); }  
    Here is initComponents() which actually does the work:
        private void initComponents() {
            depthJSlider = new javax.swing.JSlider();                                                                                              
            depthJSlider.setMajorTickSpacing(100);                                                                                                 
            depthJSlider.setMaximum(1000);                                                                                                         
            depthJSlider.setMinimum(100);                                                                                                          
            depthJSlider.setMinorTickSpacing(25);                                                                                                  
            depthJSlider.setOrientation(javax.swing.JSlider.VERTICAL);                                                                             
            depthJSlider.setPaintLabels(true);                                                                                                     
            depthJSlider.setPaintTicks(true);                                                                                                      
            depthJSlider.setSnapToTicks(true);                                                                                                     
            depthJSlider.setToolTipText("<html>\n<b>Event Log Depth Slider</b><br>\nThis slider allows you to specify the maximum number of visible\
    events<br>\nwhen the \"Refresh Log\" or \"Start Auto-refresh\" buttons are pressed.</html>");                                                 
            depthJSlider.setMaximumSize(null);                                                                                                     
            depthJSlider.setMinimumSize(null);                                                                                                     
            depthJSlider.setPreferredSize(null);                                                                                                   
            gridBagConstraints = new java.awt.GridBagConstraints();                                                                                
            gridBagConstraints.gridx = 0;                                                                                                          
            gridBagConstraints.gridy = 0;                                                                                                          
            gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;                                                                        
            gridBagConstraints.weighty = 1.0;                                                                                                      
            gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);                                                                          
            tableJPanel.add(depthJSlider, gridBagConstraints);                                                                                     
             }Does anyone have any ideas at all why some of the labels might be missing?
    (Please drop a line to [email protected] if you have any thoughts!)
    Sincerely,
    Ian

    No problems in j2se 1.5.0
    import java.awt.*;
    import javax.swing.*;
    public class SliderTest {
        private JSlider getSlider() {
            JSlider slider = new javax.swing.JSlider();
            slider.setMajorTickSpacing(100);
            slider.setMaximum(1000);
            slider.setMinimum(100);
            slider.setMinorTickSpacing(25);
            slider.setOrientation(javax.swing.JSlider.VERTICAL);
            slider.setPaintLabels(true);
            slider.setPaintTicks(true);
            slider.setSnapToTicks(true);
            slider.setToolTipText("<html><b>Event Log Depth Slider</b>" +
                            "<br>This slider allows you to specify the maximum " +
                            "number of visible events<br>when the \"Refresh Log\" " +
                            "or \"Start Auto-refresh\" buttons are pressed.</html>");
            slider.setMaximumSize(null);
            slider.setMinimumSize(null);
            slider.setPreferredSize(null);
            return slider;
        private JPanel getPanel() {
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
            gridBagConstraints.weighty = 1.0;
            gridBagConstraints.weightx = 1.0;
            gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
            for(int j = 0; j < 10; j++)
                panel.add(getSlider(), gridBagConstraints);
            return panel;
        public static void main(String[] args) {
            SliderTest test = new SliderTest();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getPanel());
            f.setSize(800,400);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

Maybe you are looking for

  • Using Photoshop on Windows 8.1 and on Mac

    I currently have a Photoshop CC license that I use on Windows 8.1 I plan to buy a MacBook pro. Can I use same license on Mac and still occasionaly use it on my Windows machine?

  • No standard agreement found for BS_A  ,, BS_B

    Hi Experts, We are getting a very common error " No standard agreement found for BS_A  ,, BS_B  https://abc.com,SIOA_forcast,,, There interface  was succsfully executing few days back. Here are some information abount the interafce. 1) JMS to IDOC 2)

  • NEWBIE: Reference Image on filesystem - how to?

    I have APEX 3.2 running with Oracle 11.2 (with EPG configured). I have a need to reference an image that sits out on the filesystem, not in the XML DB. Is there a way to accomplish this? I cannot upload the image into the database because based on va

  • Obsolete dictionary objects in ECC 6.0

    Hi all,       Will you tell me where i can find the obsolete dictionary objects along with the replacement in ECC 6.0. I got it for FUNCTIONAL MODULES ,  need it for other dictionary objects. Thanks in advance... Thanks & regards,       Navina.V.

  • My inbox has disappeared and i cannot send emails

    inbox has disappeared and I cannot send emails.  I have deleted  my account and set it up again.  Called time warner, they tried their best to help me.  It just would not send emails and they told me its an apple issue.