java swing中有什么方法可以显示带有不同消息的工具提示,实际上我正在开发一个应用程序,我必须在系统任务托盘中的工具提示上更新应用程序的当前状态。提前致谢。
问问题
1246 次
3 回答
7
+1 丹和纪尧姆·波莱特。只需setToolTipText()
在trayIcon
组件上使用。
我为你做了一个简短的例子。
它将创建一个TrayIcon
并将其添加到SystemTray
. 之后ToolTip
将TrayIcon
每 5 秒更新一次:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class SystemTrayExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SystemTrayExample().createAndAddTrayIcon();
}
});
}
private void createAndAddTrayIcon() {
try {
initComponents();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
private void initComponents() throws MalformedURLException {
//Check the SystemTray is supported
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final PopupMenu popup = new PopupMenu();
final TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().createImage(new URL("http://docs.oracle.com/javase/tutorial/uiswing/examples/misc/TrayIconDemoProject/src/misc/images/bulb.gif")));
trayIcon.setToolTip("I am the initial message");
final SystemTray tray = SystemTray.getSystemTray();
// Create a pop-up menu components
MenuItem exitItem = new MenuItem("Exit");
exitItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//Add components to pop-up menu
popup.add(exitItem);
//set popmenu
trayIcon.setPopupMenu(popup);
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
}
int delay = 5000; //milliseconds
final Timer timer = new Timer(delay, new ActionListener() {
int count = 1;
@Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Updating on EDT " + (SwingUtilities.isEventDispatchThread() ? "Yes" : "No"));
if (count == 3) {
trayIcon.setToolTip("I am the last message");
((Timer) evt.getSource()).stop();//stop timer
}
if (count == 2) {//check if we should change tooltip
trayIcon.setToolTip("I am the second message");
}
if (count == 1) {
trayIcon.setToolTip("I am the first message");
}
count++;
}
});
timer.start();//start timer to change tooltip
}
}
于 2012-10-04T12:25:05.470 回答
3
因为TrayIcon
,你有方法trayIcon.setToolTip
。您可以随时调用它,它会立即更新,即使在将托盘图标添加到系统托盘之后也是如此。
于 2012-10-04T12:15:21.213 回答
3
JComponent
您可以通过调用该setToolTipText()
方法在运行时更改 any 的工具提示。
于 2012-10-04T11:55:17.363 回答