Solved

getting a JSlider to not go over a certain value

Posted on 2004-08-23
15
589 Views
Last Modified: 2008-01-16
Hi all,

I would like my JSlider to "snap back"  (or just stop dead) when it goes above a certain value.  I can make its value do this, but I want the actual slider UI to stop so the user can see he has reached the max value.

Here is the code so far:

if (value > parentGUI.getMaxPopulation()) {
        value = parentGUI.getMaxPopulation();
        slider.setValue(value);
}

With this code, the slider just keeps on going up as the user slides it, even though the value doesn't.  The only way I have found to stop it is to call slider.updateUI().   However it seems this is a misuse of the updateUI function and it actually can cause a crash, so I need another way.

Just for background as to why I want to do this:  the slider is part of a group of JSliders each of which can be "locked".  The total value of all the JSliders mustn't go above the maximum value, so if one is locked the others have a new maximum value.
0
Comment
Question by:Dawkins
  • 5
  • 4
  • 2
  • +2
15 Comments
 
LVL 9

Expert Comment

by:DrWarezz
ID: 11874034
perhaps try this:

repaint();

Good luck,
[r.D]
0
 
LVL 9

Expert Comment

by:DrWarezz
ID: 11874044
So:

if (value > parentGUI.getMaxPopulation()) {
        value = parentGUI.getMaxPopulation();
        slider.setValue(value);
        repaint();
}
0
 

Author Comment

by:Dawkins
ID: 11875103
I tried repaint and also all these! ...

        slider.revalidate();
        slider.doLayout();
        slider.invalidate();
        slider.validate();

None stop the slider from sliding above the max value.
0
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
LVL 92

Expert Comment

by:objects
ID: 11875294
> With this code, the slider just keeps on going up as the user slides it, even though the value doesn't.

Can you post a small compilable example that demonstrates the problem.
0
 

Author Comment

by:Dawkins
ID: 11876223
>Can you post a small compilable example that demonstrates the problem.

Yep, this should illustrate the problem:

----------------------------------------------------

import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

public class SliderExample implements ChangeListener{
 
  int maximumValue = 60;
 
  public SliderExample() {
  }
 
  public void stateChanged(ChangeEvent e) {
    JSlider slider = (JSlider) e.getSource();
    int value = slider.getValue();
    System.out.println("User setting value of: " + value);
    if (value > maximumValue) {
      System.out.println("Value is greater than 60!  I'd like it to stop now!");
      slider.setValue(maximumValue);
      //slider.updateUI(); // This works but seems a real hack - and it causes crashes
    }
  }

   public static void main(String args[]) {
     SliderExample sliderExample = new SliderExample();
     JFrame frame = new JFrame();
     JSlider slider = new JSlider();
     slider.addChangeListener(sliderExample);
     frame.getContentPane().add(slider);
     frame.setSize(600,400);
     frame.show();
   }
}
0
 

Author Comment

by:Dawkins
ID: 11876403
Just a side note:

To see the crash caused by inserting "slider.updateUI();", increase the slider to 70 then click on the slider somewhere above the 60 mark and it throws a null pointer exception.
0
 
LVL 92

Expert Comment

by:objects
ID: 11876507
Why don't you set the maximum value for the slider?
0
 
LVL 35

Expert Comment

by:girionis
ID: 11878710
>  //slider.updateUI(); // This works but seems a real hack - and it causes crashes

What crashes does it cause?
0
 

Author Comment

by:Dawkins
ID: 11884146
> Why don't you set the maximum value for the slider?
That makes the far right edge of the slider the maximum value, which is not what I want.  I have a series of sliders which interact with each other so that they always have the same.  If you increase one, it decreases the others.  You can also lock them, and so if you lock one at 40, then the maximum the other two can go to is now 60.

> What crashes does it cause?
In the example that I posted, if you increase the slider to 60, then click on the slider somewhere in the 60-100 range you will see the crash.  It has something to do with setting the sliders "rectangle" value to null when you call updateUI.  I found it hard to debug the SDK files because JBuilder doesn't let you see method variables in the SDK class files when you are debugging for some reason.
0
 
LVL 35

Expert Comment

by:girionis
ID: 11884270
Yes you are right, it throws a npe. But I do not see it affects the functionallity. Maybe you could leave it like that (with the npe)?
0
 
LVL 1

Accepted Solution

by:
SlimHealer earned 125 total points
ID: 11884912
There are a couple of things going on here.

1) As a result of the call to setValue(), you end up firing a new event from inside the handler to an event -- generally this causes problems.  Using invokeLater() fixes this

2) You are way too many events.  Using getValueIsChanging() addresses this:

Here's a re-worked version of your example without the updateUI() call:


import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

public class TestCase implements ChangeListener{
 int maximumValue = 60;
      
 public TestCase() {
 }
 
 public void stateChanged(ChangeEvent e) {
  final JSlider slider = (JSlider) e.getSource();
  int value = slider.getValue();
  System.out.println("User setting value of: " + value);
  if ((value > maximumValue) && !slider.getValueIsAdjusting() ) {
        javax.swing.SwingUtilities.invokeLater( new Runnable() {
       public void run() {
         System.out.println("Value is greater than 60!       I'd like it to stop now!");
            slider.setValue(maximumValue);
       }
    });        
   }
  }

       public static void main(String args[]) {
        TestCase sliderExample = new TestCase();
        JFrame frame = new JFrame();
        JSlider slider = new JSlider();
        slider.addChangeListener(sliderExample);
        frame.getContentPane().add(slider);
        frame.setSize(600,400);
        frame.show();
       }
}




0
 
LVL 92

Expert Comment

by:objects
ID: 11887450
Use a custom BoundedRangeModel to limit the value as required.
0
 
LVL 1

Expert Comment

by:SlimHealer
ID: 11887754
Could you say more, objects?  I experimented for a while with a custom BoundedRangeModel and was unable to get it to pin the UI as requested.  I'd be interested in any insight you could offer.
0
 
LVL 92

Expert Comment

by:objects
ID: 11888194
If I get some time I'll see what I can come up with.
0
 

Author Comment

by:Dawkins
ID: 11915935
Thanks SlimHealer that seems to do the trick
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Java Server Faces parameter pass? 6 48
Java Loop 6 59
maven module vs maven project 3 22
JAVA API design with micro service cloud in mind 1 13
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question