7

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?

Vitalij Kornijenko
  • 559
  • 1
  • 10
  • 22
  • what do you mean by something happened in the program. – Braj Jul 18 '14 at 20:43
  • When a certain method finished working or when an IF statement returns true. – Vitalij Kornijenko Jul 18 '14 at 20:44
  • 1
    possible duplicate of [How to create a notification in swing](http://stackoverflow.com/questions/3240415/how-to-create-a-notification-in-swing) – Frakcool Jul 18 '14 at 20:45
  • @Frakcool nope, they are talking about notifications in tray area, that doesn't correlate to this topic. – Vitalij Kornijenko Jul 18 '14 at 20:49
  • possible duplicate of [How can I flash the Windows taskbar using Swing?](http://stackoverflow.com/questions/489255/how-can-i-flash-the-windows-taskbar-using-swing) – Knox Jul 18 '14 at 21:05
  • @VitalijKornijenko yeah you're right... sadly I can't take off my flag... let's wait until it gets rejected :) – Frakcool Jul 18 '14 at 21:07
  • 2
    Sadly, there's no way to do this from within Java itself, this is native concept. You will need to investigate a JNI/JNA solution – MadProgrammer Jul 18 '14 at 21:29

1 Answers1

5

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();
    }
});
Braj
  • 46,415
  • 5
  • 60
  • 76