简体   繁体   中英

How to make JFrame alert in taskbar?

I was wondering if Java or JFrame can alert user when something happened in the program. For example, when in Skype you receive a new message, Skype icons background changes to yellow. “你收到了一条新消息!”

Can I do this in Java?

At least you can change the icon of the JFrame by calling JFrame#setIconImage() method that looks like a notification and also change the title as well if needed.

Create a icon as you want to show when there is any notification and set the icon from the code wherever you want.


To create a glow (blink) effect you can use two images and swap at a interval if window in minimized form using Swing Timer and stop the timer when window is again deiconified.

Read more How to Use Swing Timers

sample code:

private boolean swap;
private Timer timer;

....

final Image onImage = new ImageIcon(ImageIO.read(new File("resources/1.png"))).getImage();
final Image offImage = new ImageIcon(ImageIO.read(new File("resources/2.png"))).getImage();

// interval of 500 milli-seconds
timer = new Timer(500, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        if (swap) {
            setIconImage(onImage);
        } else {
            setIconImage(offImage);
        }
        swap = !swap;
    }
});
timer.setRepeats(true);

// check whether window is in ICONIFIED state or not
if (getExtendedState() == JFrame.ICONIFIED) {
    timer.start();
}


addWindowListener(new WindowAdapter() {

    public void windowDeiconified(WindowEvent e) {
        // set the icon back to default when window is DEICONIFIED 
        timer.stop();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM