java TrayIcon使用具有透明背景的图像

2022-09-01 23:21:34

我使用以下代码在Windows和Linux中设置托盘图标。它在Windows中工作得很好,在Linux中工作得很好。在Linux(Ubuntu)中,我的面板设置为(有点)透明,当我添加GIF(具有透明背景)时,图标的背景显示为灰色和丑陋(见图像,绿色菱形“!”)....关于如何使我正在添加的GIF图像“保留”其透明背景的任何想法?

可选文字 http://unarm.org/stackoverflow/panel_task.jpg

和我正在使用的图像,如果你想测试:

替代文本 http://unarm.org/stackoverflow/green_info.gif

import java.awt.*;
import java.awt.event.*;

public class TrayFun {


  static class ShowMessageListener implements ActionListener {
    TrayIcon trayIcon;
    String title;
    String message;
    TrayIcon.MessageType messageType;
    ShowMessageListener(
        TrayIcon trayIcon,
        String title,
        String message,
        TrayIcon.MessageType messageType) {
      this.trayIcon = trayIcon;
      this.title = title;
      this.message = message;
      this.messageType = messageType;
    }
    public void actionPerformed(ActionEvent e) {
      trayIcon.displayMessage(title, message, messageType);
    }
  }

  public static void main(String args[]) {
    Runnable runner = new Runnable() {
      public void run() {
        if (SystemTray.isSupported()) {
          final SystemTray tray = SystemTray.getSystemTray();
          Image image = Toolkit.getDefaultToolkit().getImage("green_info.png");
          PopupMenu popup = new PopupMenu();
          final TrayIcon trayIcon = new TrayIcon(image, "The Tip Text", popup);
          trayIcon.setImageAutoSize(true);

          MenuItem item = new MenuItem("Close");
      item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
          tray.remove(trayIcon);
            }
      });
          popup.add(item);
          try {
            tray.add(trayIcon);
          } catch (AWTException e) {
            System.err.println("Can't add to tray");
          }
        } else {
          System.err.println("Tray unavailable");
        }
      }
    };
    EventQueue.invokeLater(runner);
  }
}

答案 1

问题在于 sun.awt.X11.XTrayIconPeer.IconCanvas.paint() 方法!

在绘画之前,只需绘制一个图标Canvas背景颜色的矩形,即可轻松清除图标背景,以允许图像动画。

public void paint(Graphics g) {
    if (g != null && curW > 0 && curH > 0) {
        BufferedImage bufImage = new BufferedImage(curW, curH, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gr = bufImage.createGraphics();
        if (gr != null) {
            try {
                gr.setColor(getBackground());
                gr.fillRect(0, 0, curW, curH);
                gr.drawImage(image, 0, 0, curW, curH, observer);
                gr.dispose();

                g.drawImage(bufImage, 0, 0, curW, curH, null);
            } finally {
                gr.dispose();
            }
        }
    }
}

请参见: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6453521


答案 2

对于那些寻找“真正”解决方案的人,我开发了一个小型库,它能够显示尊重透明度的托盘图标,并且还接受SVG图标(适用于所有平台):

http://skype2gmail.blogspot.com/2011/05/java-tray-icon-transparency.html

它是一个开源库,源代码可以在这里找到:

https://github.com/taksan/native-tray-adapter

该库通过在Linux下运行时提供JNI替代方案(使用GTK)来解决此问题。


推荐