我在这里设置了一个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;
}

最佳答案

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

基本上,您是在阻止事件调度线程,从而阻止其实际绘制...

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将您的大多数重画请求合并到尽可能少的事件中,以保持性能。因此,当您“阻止” 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

07-24 09:19