Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 事件发生时,重绘功能不起作用_Java_Swing_Jbutton_Background Color_Thread Sleep - Fatal编程技术网

Java 事件发生时,重绘功能不起作用

Java 事件发生时,重绘功能不起作用,java,swing,jbutton,background-color,thread-sleep,Java,Swing,Jbutton,Background Color,Thread Sleep,当事件发生时,我正在尝试更改按钮背景颜色10次 不要在Swing事件线程上调用Thread.sleep(…),因为这会使整个Swing GUI处于睡眠状态。换句话说,您的GUI不进行绘制,不接受任何用户输入或交互,并且在事件发生时(也称为事件调度线程或EDT)变得完全无用。改用摆动计时器。有关此方面的更多帮助,请查看 还可以查看一些答案,包括mKorbel的答案。很高兴您能使用它。考虑一下,在课堂开始时只创建一次随机对象。没有必要继续重新创建它。 private void jButton2Ac

事件发生时,我正在尝试更改按钮背景颜色10次


不要在Swing事件线程上调用Thread.sleep(…),因为这会使整个Swing GUI处于睡眠状态。换句话说,您的GUI不进行绘制,不接受任何用户输入或交互,并且在事件发生时(也称为事件调度线程或EDT)变得完全无用。改用摆动计时器。有关此方面的更多帮助,请查看


还可以查看一些答案,包括mKorbel的答案。

很高兴您能使用它。考虑一下,在课堂开始时只创建一次随机对象。没有必要继续重新创建它。
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        for (int i = 0; i < 10; ++i) {
            Random r = new Random();
            jButton2.setBackground(new Color(r.nextInt(150), r.nextInt(150), r.nextInt(150)));
            jButton2.repaint();
            Thread.sleep(200);
        }
    } catch (Exception e) {
        System.out.println(e.toString());
    }

}
int x = 0;
Timer timer;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    timer = new Timer(1000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Random r = new Random();
            jButton2.setBackground(new Color(r.nextInt(150), r.nextInt(150), r.nextInt(150)));
            jButton2.repaint();
            if(x==10){
                timer.stop();
                x=0;
            } else{
                x++;
            }
        }
    });
    timer.start();
}