Nimtiz
Nimtiz

Reputation: 5

How can I make a jslider actually affect things as it slides?

I have set up an area where a jslider should alter the delay of some dots in a jpanel here

    JSlider source = (JSlider)e.getSource();
        if (source == speedSlider) {
            if (source.getValueIsAdjusting()) {
                GraphicsDisplay.delay += 100000;                  
            }
        }

The delay is put into affect by the following

 public static boolean stop = true ;          
 public static long delay = 3000000 ;


 public void paint ( Graphics g2 ) {

    //code making dots up here...


         int a;
         if ( !stop ) {
            for ( a=0; a<delay; a++ ) ; 
            moveDot ( ) ;  
         }
   repaint();
   }     

I can't get the slider to do anything. And I know it has something to do with

if (source.getValueIsAdjusting()) {
    GraphicsDisplay.delay += 100000;                  
}

Upvotes: 0

Views: 119

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

The problem isn't with the slider, it's with your painting...

Basically, you are blocking the Event Dispatching Thread, preventing it from actually painting...

public void paint ( Graphics g2 ) {
    // Let's ignore the fact that you haven't called super.paint here...
    //code making dots up here...
    int a;
    if ( !stop ) {
        // Block the EDT, stop all painting and event processing until this for
        // exist...
        for ( a=0; a<delay; a++ ) ; 
        moveDot ( ) ;  
    }
    // This is a very bad idea inside any paint method...
    repaint();
}     

Basically, what's happening, is the RepaintManager is consolidating most of your repaint requests down to as few events as possible, in order to maintain performance. So while you "block" the EDT, you paint requests are been queued, but not processed, the repaint manager is making decisions that may also consolidate those requests down to a few events in order to maintain performance.

A better solution would be to use a Swing Timer. See How to Use Swing Timers

private javax.swing.Timer timer;
//...

timer = new Timer(delay, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        moveDot();
        repaint();
    }
});
timer.start();

//...

if (source.getValueIsAdjusting()) {
    timer.stop();
    timer.setDelay(source.getValue());
    timer.start();
}

Your use of static variables is also a little scary...

ps- I forgot to mention, you should avoid overriding paint and instead use paintComponent, making sure you call super.paintComponent first...See Perfoming Custom Painting

Upvotes: 2

Related Questions