Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. "You have received a new message!"

Can I do this in Java?

like image 930
Vitalij Kornijenko Avatar asked Jul 18 '14 20:07

Vitalij Kornijenko


1 Answers

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();
    }
});
like image 148
Braj Avatar answered Sep 27 '22 21:09

Braj