下面列出了怎么用java.awt.SystemTray的API类实例代码及写法,或者点击链接到github查看源代码。
static void stopBackground(boolean showAlert) {
inBackground = false;
executor.shutdownNow();
if (SwingUtilities.isEventDispatchThread()) {
SystemTray.getSystemTray().remove(trayIcon);
} else {
SwingUtilities.invokeLater(() -> SystemTray.getSystemTray().remove(trayIcon));
}
if (showAlert) {
Utils.runSafe(() -> {
Alert alert = new Alert(Alert.AlertType.INFORMATION,
"The background process has been cancelled",
ButtonType.OK);
alert.showAndWait();
});
}
System.out.println("Stopped background");
}
private void initTray() throws AWTException {
if (SystemTray.isSupported()) {
// 获得系统托盘对象
SystemTray systemTray = SystemTray.getSystemTray();
// 获取图片所在的URL
URL url = Thread.currentThread().getContextClassLoader().getResource(ICON_PATH);
// 为系统托盘加托盘图标
Image trayImage = Toolkit.getDefaultToolkit().getImage(url);
Dimension trayIconSize = systemTray.getTrayIconSize();
trayImage = trayImage.getScaledInstance(trayIconSize.width, trayIconSize.height, Image.SCALE_SMOOTH);
trayIcon = new TrayIcon(trayImage, "Proxyee Down");
systemTray.add(trayIcon);
loadPopupMenu();
//双击事件监听
trayIcon.addActionListener(event -> Platform.runLater(() -> loadUri(null, true)));
}
}
public static void main(String[] args) throws Exception {
if (!SystemTray.isSupported()) {
System.out.println("SystemTray not supported on the platform." +
" Marking the test passed.");
} else {
if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
System.err.println(
"Test can fail on Windows platform\n"+
"On Windows 7, by default icon hides behind icon pool\n" +
"Due to which test might fail\n" +
"Set \"Right mouse click\" -> " +
"\"Customize notification icons\" -> \"Always show " +
"all icons and notifications on the taskbar\" true " +
"to avoid this problem.\nOR change behavior only for " +
"Java SE tray icon and rerun test.");
}
ActionEventTest test = new ActionEventTest();
test.doTest();
test.clear();
}
}
private void initializeGUI() {
icon = new TrayIcon(
new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB), "ti");
icon.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
actionPerformed = true;
int md = ae.getModifiers();
int expectedMask = ActionEvent.ALT_MASK | ActionEvent.CTRL_MASK
| ActionEvent.SHIFT_MASK;
if ((md & expectedMask) != expectedMask) {
clear();
throw new RuntimeException("Action Event modifiers are not"
+ " set correctly.");
}
}
});
try {
SystemTray.getSystemTray().add(icon);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws Exception {
if (!SystemTray.isSupported()) {
System.out.println("SystemTray not supported on the platform "
+ "under test. Marking the test passed");
} else {
String osName = System.getProperty("os.name").toLowerCase();
if (osName.startsWith("mac")) {
isMacOS = true;
} else if (osName.startsWith("win")) {
isWinOS = true;
} else {
isOelOS = SystemTrayIconHelper.isOel7();
}
new TrayIconMouseTest().doTest();
}
}
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
if (trayIcon != null) {
SystemTray.getSystemTray().remove(trayIcon);
}
if (mCurrentAudioMonitor != null) {
mCurrentAudioMonitor.stopMonitoring();
mCurrentAudioMonitor = null;
}
if (mRemote != null) {
mRemote.shutdown();
mRemote = null;
}
if (mShortcuts != null) {
mShortcuts.stop();
}
}
/**
* Start next upload if any.. Decrements the current uploads averageProgress and
* updates the queuing mechanism.
*/
public void startNextUploadIfAny() {
currentlyUploading--;
//If no more uploads in queue and no more uploads currently running, reset the title
if (getQueuedUploadCount() == 0 && currentlyUploading == 0){
setFrameTitle();
try{
//If the tray icon is activated, then display message
if(SystemTray.getSystemTray().getTrayIcons().length > 0) {
SystemTray.getSystemTray().getTrayIcons()[0].displayMessage(Translation.T().neembuuuploader(), Translation.T().allUploadsCompleted(), TrayIcon.MessageType.INFO);
}
}catch(UnsupportedOperationException a){
//ignore
}
} else {
updateQueue();
}
}
private void setUpTrayIcon() {
if (SystemTray.isSupported()) {
//trayIcon.setImageAutoSize(true); It renders the icon very poorly.
//So we render the icon ourselves with smooth settings.
{
Dimension d = SystemTray.getSystemTray().getTrayIconSize();
trayIcon = new TrayIcon(getIconImage().getScaledInstance(d.width, d.height, Image.SCALE_SMOOTH));
}
//trayIcon = new TrayIcon(getIconImage());
//trayIcon.setImageAutoSize(true);
trayIcon.setToolTip(Translation.T().trayIconToolTip());
trayIcon.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
NULogger.getLogger().info("System tray double clicked");
setExtendedState(JFrame.NORMAL);
setVisible(true);
repaint();
SystemTray.getSystemTray().remove(trayIcon);
}
});
}
}
public void hideToTray() {
if (sysTray == null || SystemTray.isSupported() == false) {
System.out.println("GuiSwing::hideToTray SystemTray not supported!");
return;
}
try {
trayIcon = getTrayIcon();
sysTray.add(trayIcon);
}
catch (AWTException e) {
System.out.println("GuiSwing::hideToTray an error occured while trying to add system tray icon (exception: " + e + ")");
return;
}
setVisible(false);
}
void setTray() {
if (!Config.getInstance().getBoolean(Config.MAIN_TRAY)) {
this.removeTray();
return;
}
if (!SystemTray.isSupported()) {
LOGGER.info("tray icon not supported");
return;
}
if (mTrayIcon == null)
mTrayIcon = this.createTrayIcon();
SystemTray tray = SystemTray.getSystemTray();
if (tray.getTrayIcons().length > 0)
return;
try {
tray.add(mTrayIcon);
} catch (AWTException ex) {
LOGGER.log(Level.WARNING, "can't add tray icon", ex);
}
}
private void enableTray(final Stage stage) {
try {
ContextMenu menu = new ContextMenu();
MenuItem updateMenuItem = new MenuItem();
MenuItem showMenuItem = new MenuItem();
showMenuItem.setText("查看群信息");
updateMenuItem.setText("修改群信息");
menu.getItems().add(showMenuItem);
menu.getItems().add(updateMenuItem);
menu.getItems().add(new MenuItem("好好的事实的话"));
menu.getItems().add(new MenuItem("好好的事实的话"));
menu.getItems().add(new MenuItem("好好的事实的话"));
menu.getItems().add(new MenuItem("好好的事实的话"));
menu.getItems().add(new MenuItem("好好的事实的话"));
SystemTray tray = SystemTray.getSystemTray();
BufferedImage image = ImageIO.read(OnlyTrayIconDemo.class.getResourceAsStream("tray.png"));
// Image image = new
// ImageIcon("Resources/Images/Logo/logo_16.png").getImage();
trayIcon = new OnlyTrayIcon(image, "自动备份工具");
trayIcon.setToolTip("自动备份工具");
trayIcon.setContextMenu(menu);
tray.add(trayIcon);
} catch (Exception e) {
e.printStackTrace();
}
}
private void initTray() {
try {
if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();
tray.add(trayIcon);
}
} catch (AWTException ex) {
ex.printStackTrace();
}
}
private void start(String[] args) {
SystemTray tray = SystemTray.getSystemTray();
TrayIcon icon = new TrayIcon(Toolkit.getDefaultToolkit().createImage(
getClass().getResource(
"/com/ramussoft/gui/server/application.png")),
getString("Server") + " " + Metadata.getApplicationName(),
createPopupMenu());
icon.setImageAutoSize(true);
try {
tray.add(icon);
} catch (AWTException e) {
e.printStackTrace();
}
}
private void createSystemTrayIcons() {
final TrayIcon trayIcon = new TrayIcon(createSystemTrayIconImage());
trayIcon.setImageAutoSize(true);
trayIcon.setToolTip("Update Popup Menu items");
try {
trayIcon.setPopupMenu(createPopupMenu(trayIcon, 2));
SystemTray.getSystemTray().add(trayIcon);
} catch (AWTException ex) {
throw new RuntimeException("System Tray cration failed");
}
}
public static void main(final String[] args) throws Exception {
if (SystemTray.isSupported()) {
UpdatePopupMenu updatePopupMenu = new UpdatePopupMenu();
updatePopupMenu.createInstructionUI();
updatePopupMenu.createSystemTrayIcons();
mainThread = Thread.currentThread();
try {
mainThread.sleep(testTimeOut);
} catch (InterruptedException ex) {
if (!testPassed) {
throw new RuntimeException("Updating TrayIcon popup menu"
+ " items FAILED");
}
} finally {
cleanUp();
}
if (!isInterrupted) {
throw new RuntimeException("Test Timed out after "
+ testTimeOut / 1000 + " seconds");
}
} else {
System.out.println("System Tray is not supported on this platform");
}
}
private static void removeIcon() {
TrayIcon icon = iconWeakReference.get().get();
if (icon == null) {
throw new RuntimeException("Failed: TrayIcon collected too early");
}
SystemTray.getSystemTray().remove(icon);
}
private static void createSystemTrayIcon() {
final TrayIcon trayIcon = new TrayIcon(createTrayIconImage());
trayIcon.setImageAutoSize(true);
try {
// Add tray icon to system tray *before* adding popup menu to demonstrate buggy behaviour
trayIcon.setPopupMenu(createTrayIconPopupMenu());
SystemTray.getSystemTray().add(trayIcon);
iconWeakReference.set(new WeakReference<>(trayIcon));
popupWeakReference.set(new WeakReference<>(trayIcon.getPopupMenu()));
} catch (final AWTException awte) {
awte.printStackTrace();
}
}
public static void setupTray() throws AWTException {
final SystemTray tray = SystemTray.getSystemTray();
final PopupMenu popup = new PopupMenu();
final MenuItem info = new MenuItem();
final MenuItem exit = new MenuItem();
final TrayIcon trayIcon = new TrayIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB), "MLGA", popup);
try {
InputStream is = FileUtil.localResource("icon.png");
trayIcon.setImage(ImageIO.read(is));
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
info.addActionListener(e -> {
String message = "Double-Click to lock/unlock the overlay for dragging";
JOptionPane.showMessageDialog(null, message, "Information", JOptionPane.INFORMATION_MESSAGE);
});
exit.addActionListener(e -> {
running = false;
tray.remove(trayIcon);
ui.close();
System.out.println("Terminated UI...");
System.out.println("Cleaning up system resources. Could take a while...");
handle.close();
System.out.println("Killed handle.");
System.exit(0);
});
info.setLabel("Help");
exit.setLabel("Exit");
popup.add(info);
popup.add(exit);
tray.add(trayIcon);
}
synchronized void initialize() {
if (SystemTray.isSupported()) {
mainWindow = WindowManager.getDefault().getMainWindow();
mainWindowListener = new MainWindowListener();
lastWindowState = mainWindow.getExtendedState();
loadSettings();
if (!hideTrayIcon) showTrayIcon();
mainWindow.addWindowStateListener(mainWindowListener);
}
}
private void hideTrayIcon() {
SystemTray tray = SystemTray.getSystemTray();
if (tray != null) {
try {
tray.remove(trayIcon);
} catch (Exception e) {
Exceptions.printStackTrace(e);
}
}
trayIcon = null;
}
private Image createTrayImage() {
Dimension iconDimension = SystemTray.getSystemTray().getTrayIconSize();
int iconWidth = iconDimension.width;
int iconHeight = iconDimension.height;
if (iconWidth <= 16 && iconHeight <= 16)
return ImageUtilities.loadImage("org/graalvm/visualvm/modules/systray/resources/icon16.png"); // NOI18N
if (iconWidth <= 32 && iconHeight <= 32)
return ImageUtilities.loadImage("org/graalvm/visualvm/modules/systray/resources/icon32.png"); // NOI18N
return ImageUtilities.loadImage("org/graalvm/visualvm/modules/systray/resources/icon48.png"); // NOI18N
}
/**
* Create tray icon.
*
* @param icon the icon
* @param title the title
* @param frame the frame
* @return the tray icon
*/
@Nullable
public static TrayIcon createTrayIcon(@Nonnull final Image icon, @Nonnull final String title, @Nonnull final Frame frame)
{
if (!SystemTray.isSupported())
{
return null;
}
final SystemTray systemTray = SystemTray.getSystemTray();
final TrayIcon trayIcon = new TrayIcon(icon, title);
trayIcon.setImageAutoSize(true);
try
{
systemTray.add(trayIcon);
}
catch (AWTException ex)
{
log.debug("Unable to add system tray icon", ex);
return trayIcon;
}
// Bring to front when tray icon is clicked
trayIcon.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
frame.setVisible(true);
frame.setState(Frame.NORMAL); // Restore
}
});
return trayIcon;
}
public void uninstallComponents() {
try {
SystemTray.getSystemTray().remove(trayIcon);
} catch (Throwable x) {
System.err.println("Disabling tray support.");
}
}
public static void showTrayMessage(String title, String message) {
try {
SystemTray tray = SystemTray.getSystemTray();
BufferedImage image = ImageIO.read(AlertMaker.class.getResource(LibraryAssistantUtil.ICON_IMAGE_LOC));
TrayIcon trayIcon = new TrayIcon(image, "Library Assistant");
trayIcon.setImageAutoSize(true);
trayIcon.setToolTip("Library Assistant");
tray.add(trayIcon);
trayIcon.displayMessage(title, message, MessageType.INFO);
tray.remove(trayIcon);
} catch (Exception exp) {
exp.printStackTrace();
}
}
public void setIcon(boolean color) {
SystemTray tray = SystemTray.getSystemTray();
TrayIcon[] icons = tray.getTrayIcons();
if (icons.length > 0) {
String name = color ? "favicon-green.png" : "favicon-red.png";
URL url = getClass().getClassLoader().getResource(name);
Image image = Toolkit.getDefaultToolkit().getImage(url);
int trayWidth = tray.getTrayIconSize().width;
int trayHeight = tray.getTrayIconSize().height;
Image scaled = image.getScaledInstance(trayWidth, trayHeight, Image.SCALE_SMOOTH);
icons[0].setImage(scaled);
}
}
private void createGui() {
setJPopupMenu(createJPopupMenu());
try {
// TODO: Bug in setting transparency of SystemTray Icon in
// Linux - http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6453521
SystemTray.getSystemTray().add(this);
} catch (AWTException e) {
e.printStackTrace();
}
}
private void formWindowIconified(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowIconified
if (!Application.get(Settings.class).minimizetotray() || !SystemTray.isSupported() || trayIcon == null || !isActive()) {
return;
}
NULogger.getLogger().info("Minimizing to Tray");
setVisible(false);
try {
SystemTray.getSystemTray().add(trayIcon);
} catch (AWTException ex) {
setVisible(true);
Logger.getLogger(NeembuuUploader.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Creates new form SettingsManager
*/
public SettingsManager(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
//Check if Nimbus theme is available or not..
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
nimbusavailable = true;
nimbusThemeRadioButton.setEnabled(true);
break;
}
}
NULogger.getLogger().log(Level.INFO, "Nimbus theme available? : {0}", nimbusavailable);
//Check if Nimbus theme is available or not..
if (SystemTray.isSupported()) {
trayavailable = true;
minimizeToTray.setEnabled(true);
}
NULogger.getLogger().log(Level.INFO, "System Tray available? : {0}", trayavailable);
//Temporary disabling for release 2.9
settingsTabbedPanel.remove(1);
//Set location relative to NU
setLocationRelativeTo(NeembuuUploader.getInstance());
}
@Override
public void windowIconified(WindowEvent we) {
windowMinimized = true;
if (!SystemTray.isSupported()) {
return;
}
setState(JFrame.MAXIMIZED_BOTH);
setVisible(false);
}
@Override
public void windowDeiconified(WindowEvent we) {
windowMinimized = false;
if (!SystemTray.isSupported()) {
return;
}
setState(JFrame.MAXIMIZED_BOTH);
setVisible(true);
}