我正在尝试用Java模拟Objective C的NSStatusItem功能。也就是说,我正在尝试编写一个Java应用程序,它将位于Mac的菜单栏like this中。 Here's a link到Apple关于StatusBar的文档。
用Java做任何事吗?
答案 0 :(得分:8)
使用java.awt.SystemTray。我已经确认它适用于OS X Lion。根据{{3}},也可以使用SWT。
示例:
import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
public class MenuBarIconTest {
public static void main(String[] args) throws MalformedURLException {
TrayIcon trayIcon = null;
if (SystemTray.isSupported()) {
// get the SystemTray instance
SystemTray tray = SystemTray.getSystemTray();
// load an image
Image image = Toolkit.getDefaultToolkit().getImage(new URL("http://cdn1.iconfinder.com/data/icons/Hypic_Icon_Pack_by_shlyapnikova/16/forum_16.png"));
// create a action listener to listen for default action executed on the tray icon
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("action");
// execute default action of the application
// ...
}
};
// create a popup menu
PopupMenu popup = new PopupMenu();
// create menu item for the default action
MenuItem defaultItem = new MenuItem("Do the action");
defaultItem.addActionListener(listener);
popup.add(defaultItem);
/// ... add other items
// construct a TrayIcon
trayIcon = new TrayIcon(image, "Tray Demo", popup);
// set the TrayIcon properties
trayIcon.addActionListener(listener);
// ...
// add the tray image
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println(e);
}
// ...
} else {
// disable tray option in your application or
// perform other actions
//...
}
// ...
// some time later
// the application state has changed - update the image
if (trayIcon != null) {
//trayIcon.setImage(updatedImage);
}
}
}
答案 1 :(得分:0)
有一个 NICE 库可以做到这一点......我见过的最好的一个将菜单栏访问的 SWIFT 功能与 JavaFX 集成在一起......因为 FX 没有本地方式来处理菜单栏。
Here is the link 如果您有兴趣。