如何让jslider在滑动时实际影响事物?

时间:2014-03-13 22:51:37

标签: java swing jpanel jslider

我已经设置了一个区域,其中jslider应该改变jpanel中某些点的延迟

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

延迟由以下

生效
 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();
   }     

我无法让滑块做任何事情。我知道它与

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

1 个答案:

答案 0 :(得分:2)

问题不在于滑块,而在于您的绘画...

基本上,您正在阻止事件调度线程,阻止它实际绘制...

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

基本上,发生了什么,RepaintManager正在将大多数重绘请求合并到尽可能少的事件,以保持性能。所以当你&#34;阻止&#34;在EDT中,您绘制的请求已排队但未处理,重绘管理器正在做出决策,这些决策可能还会将这些请求合并到一些事件中以保持性能。

更好的解决方案是使用Swing Timer。见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();
}

您使用static变量也有点可怕......

ps-我忘记提及,你应该避免覆盖paint而是使用paintComponent,确保首先致电super.paintComponent ...见Perfoming Custom Painting