如何在Swing中使用Thread.sleep()和setBackground()创建闪光效果? [英] How to use Thread.sleep() and setBackground() to create flash effect in Swing?

查看:149
本文介绍了如何在Swing中使用Thread.sleep()和setBackground()创建闪光效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过以下方法制作闪光效果: 将(JTextArea)的背景更改为RED->然后等待1秒钟->返回WHITE. 我喜欢这样:

I would like to make flash effect by: changing the background (of a JTextArea) into RED --> then wait for 1 second --> going back to WHITE. I do like this :

JTextArea jTextArea = new JTextArea();
jTextArea.setBackGround(Color.RED);
Thread.currentThread().sleep(1000);
jTextArea.setBackGround(Color.WHITE)

但是它不起作用,我所拥有的只是白色背景,我看不到红色背景.

But it doesn't work, all what I have is the White Background, I don't see the Red one.

我怎么了?

谢谢!

推荐答案

您应该使用 Swing中的并发.请看下面的代码,并询问您无法掌握的内容.

Instead of using Thread.sleep(...), which can freeze your GUI, you should be using javax.swing.Timer. Moreover any updates to the GUI must be done on the EDT, as very much said by @MinhCatVO. For more information on the topic please refer to Concurrency in Swing. Have a look at the below code and ask what is beyond your grasp.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ColouringTextArea
{
    private JTextArea tarea;
    private Timer timer;
    private Color[] colours = {
                                Color.RED,
                                Color.BLUE,
                                Color.GREEN.darker(),
                                Color.DARK_GRAY,
                                Color.MAGENTA,
                                Color.YELLOW
                              };
    private int counter = 0;                          
    private ActionListener timerAction = new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            if (counter < colours.length)
            {
                tarea.setBackground(colours[counter]);
                counter++;
            }
            else
            {
                tarea.setBackground(Color.PINK);
                counter = 0;
            }   
        }
    };

    private void displayGUI()
    {
        JFrame frame = new JFrame("Colouring JTextArea");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel contentPane = new JPanel();
        tarea = new JTextArea(10, 10);
        contentPane.add(tarea);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

        timer = new Timer(1000, timerAction);
        timer.start();
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new ColouringTextArea().displayGUI();
            }
        });
    }
}

这篇关于如何在Swing中使用Thread.sleep()和setBackground()创建闪光效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆