Search code examples
javaawtsystem-tray

add badge to tray icon (java)


i have created a simple app in java to show a tray icon and from there show a list of JIRA issues that are assigned to me.

what i have at the moment is a tray icon that when you right click on it brungs up a popup message with the last 10 open issues assigned to me, when you click a menu item it directs you to the desired issue in your browser of choice.

What i would now like it to do is display a badge over the top of the tray icon that shows how many open issues i have. i have the code to find the number of issues but i cant for the life of me work out how to add the badge to the tray icon.

im using :

java.awt.MenuItem;
java.awt.PopupMenu;
java.awt.SystemTray;
java.awt.TrayIcon;

to create the tray icon and popup menu.

any help would be greatly appreciated

Thanks


Solution

  • Okay so i figured it out,

    first i select the original icon:

    BufferedImage im = ImageIO.read(Systray.class.getResource("icon.gif"));
    

    then i use Graphics2D to draw ontop of the image:

    Graphics2D g2 = im.createGraphics();
    
    g2.setColor(Color.BLACK);
    g2.drawString("10", 2, 10);
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(im, "png", baos);
    byte[] b = baos.toByteArray();
    

    then i create a new image icon from the byte array:

    ImageIcon imgTmp = new ImageIcon(b);
    

    finally i set the tray icon:

    _icon.setImage(imgTmp.getImage());
    

    (_icon is an instance of TrayIcon)

    i hope that this helps someone else and if you have a better solution id love to see it