私は本業のプログラマーではありません (私が持っている Java の知識は、School of Hard Knocks から得たものです)。私がしようとしているばかげた質問を許してください、そして適切に答えてください。
私が取り組んでいる Java アプリは、非常にバグのあるプラットフォームに依存しない通知 (ファイルが正常にダウンロードされたときなど) を使用します。プラットフォーム対応の通知を使用したい。Linux で通知を発生させるコードは非常に単純です。
import org.gnome.gtk.Gtk;
import org.gnome.notify.Notify;
import org.gnome.notify.Notification;
public class HelloWorld
{
public static void main(String[] args) {
Gtk.init(args);
Notify.init("Hello world");
Notification Hello = new Notification("Hello world!", "This is an example notification.", "dialog-information");
Hello.show();
}
}
Mac ではもう少し複雑ですが、それでも実行可能です。
interface NsUserNotificationsBridge extends Library {
NsUserNotificationsBridge instance = (NsUserNotificationsBridge)
Native.loadLibrary("/usr/local/lib/NsUserNotificationsBridge.dylib", NsUserNotificationsBridge.class);
public int sendNotification(String title, String subtitle, String text, int timeoffset);
}
この github リポジトリから取得できる dylib が必要です: https://github.com/petesh/OSxNotificationCenter
Windows の方法は次のとおりです。
import java.awt.*;
import java.awt.TrayIcon.MessageType;
public class TrayIconDemo {
public static void main(String[] args) throws AWTException {
if (SystemTray.isSupported()) {
TrayIconDemo td = new TrayIconDemo();
td.displayTray();
} else {
System.err.println("System tray not supported!");
}
}
public void displayTray() throws AWTException {
//Obtain only one instance of the SystemTray object
SystemTray tray = SystemTray.getSystemTray();
//If the icon is a file
Image image = Toolkit.getDefaultToolkit().createImage("icon.png");
//Alternative (if the icon is on the classpath):
//Image image = Toolkit.getDefaultToolkit().createImage(getClass().getResource("icon.png"));
TrayIcon trayIcon = new TrayIcon(image, "Tray Demo");
//Let the system resize the image if needed
trayIcon.setImageAutoSize(true);
//Set tooltip text for the tray icon
trayIcon.setToolTip("System tray icon demo");
tray.add(trayIcon);
trayIcon.displayMessage("Hello, World", "notification demo", MessageType.INFO);
}
}
ポイントは、これらのスニペットを適切なプラットフォームでのみ実行することです。依存関係が存在しないため、たとえば Windows で GTK メソッドを Java にコンパイルさせたくありません。
Java が認識できるようにするにはどうすればよいでしょうか。たとえば、「Mac システム用にコンパイルしているので、Mac バージョンのコードを使用しています」のようになります。