【问题标题】:repaint function not work when event happen事件发生时重绘功能不起作用
【发布时间】:2013-05-04 08:12:30
【问题描述】:

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


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

【问题讨论】:

  • 很高兴你已经成功了。考虑在课程开始时只创建一次 Random 对象。没有必要重新创建它。

标签: java swing jbutton background-color thread-sleep


【解决方案1】:

不要在 Swing 事件线程上调用 Thread.sleep(...),因为这会使整个 Swing GUI 进入睡眠状态。换句话说,您的 GUI 不进行绘画,根本不接受用户输入或交互,并且在事件(也称为 Event Dispatch Thread 或 EDT)。请改用摇摆计时器。请查看Swing Timer Tutorial 以获得更多帮助。

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

【讨论】:

    猜你喜欢
    • 2018-10-07
    • 1970-01-01
    • 2022-11-12
    • 2019-05-15
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多