TrayIcon
有点问题,因为它不是Component
Java AWT / Swing 组件的其余部分。我找到了解决方法,但它与工具提示不完全相同。TrayIcon
有displayMessage
可以用来代替工具提示的方法。我试图让它表现得像工具提示(悬停时显示),但并非所有鼠标事件都受支持,因此必须始终显示消息,或单击图标。我也对在其他操作系统上显示消息的实现有些担忧。我只在 MS Windows XP SP3 上测试过,结果如下(每 1 秒更新一次):
这是可运行的示例(您需要 image.jpeg 才能运行):
import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.Timer;
public class TestTray {
final ActionListener menuItemCloseAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
};
final MenuItem menuItemClose = new MenuItem("Close");
final PopupMenu menu = new PopupMenu();
final Image image;
{
Image tmp = null;
try {
tmp = ImageIO.read(TestTray.class.getResourceAsStream("image.jpeg"));
} catch (IOException e) {
e.printStackTrace();
}
image = tmp;
}
final TrayIcon trayIcon = new TrayIcon(image,null,menu);
final SystemTray tray = SystemTray.getSystemTray();
final DateFormat dateFormat = new SimpleDateFormat("HH:MM:ss");
final ActionListener timerAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String msg = "Time is: "+ dateFormat.format(new Date());
//trayIcon.setToolTip(msg);
trayIcon.displayMessage("", msg, MessageType.NONE);
}
};
final Timer timer = new Timer(100, timerAction);
{
menu.add(menuItemClose);
menuItemClose.addActionListener(menuItemCloseAction);
try {
tray.add(trayIcon);
} catch (AWTException e) {
e.printStackTrace();
}
timer.start();
}
public static void main(String[] args) {
new TestTray();
}
}