Java Code Examples for java.awt.SystemTray#isSupported()

The following examples show how to use java.awt.SystemTray#isSupported() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DownApplication.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
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)));
  }
}
 
Example 2
Source File: ActionEventTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example 3
Source File: GuiSwing.java    From sheepit-client with GNU General Public License v2.0 6 votes vote down vote up
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);
	
}
 
Example 4
Source File: TrayManager.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example 5
Source File: GuiSwing.java    From sheepit-client with GNU General Public License v2.0 5 votes vote down vote up
public void restoreFromTray() {
	if (sysTray != null && SystemTray.isSupported()) {
		sysTray.remove(trayIcon);
		setVisible(true);
		setExtendedState(getExtendedState() & ~JFrame.ICONIFIED & JFrame.NORMAL); // for toFront and requestFocus to actually work
		toFront();
		requestFocus();
	}
}
 
Example 6
Source File: TrayViewImpl.java    From oim-fx with MIT License 5 votes vote down vote up
private void initTray() {
	try {
		if (SystemTray.isSupported()) {
			SystemTray tray = SystemTray.getSystemTray();
			tray.add(trayIcon);
		}
	} catch (AWTException ex) {
		ex.printStackTrace();
	}
}
 
Example 7
Source File: GuiSwing.java    From sheepit-client with GNU General Public License v2.0 5 votes vote down vote up
@Override public void updateTrayIcon(Integer percentage) {
	// update the app icon on the app bar
	Image img = extractImageFromSprite(percentage);
	setIconImage(img);
	
	// if the app supports the system tray, update as well
	if (sysTray != null && SystemTray.isSupported()) {
		if (trayIcon != null) {
			trayIcon.setImage(img);
			trayIcon.setImageAutoSize(true);        // use this method to ensure that icon is refreshed when on
			// the tray
		}
	}
}
 
Example 8
Source File: MainForm.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
@Override
public void windowDeiconified(WindowEvent we) {
	windowMinimized = false;
	if (!SystemTray.isSupported()) {
		return;
	}
	setState(JFrame.MAXIMIZED_BOTH);
	setVisible(true);
}
 
Example 9
Source File: MainForm.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
@Override
public void windowIconified(WindowEvent we) {
	windowMinimized = true;
	if (!SystemTray.isSupported()) {
		return;
	}
	setState(JFrame.MAXIMIZED_BOTH);
	setVisible(false);
}
 
Example 10
Source File: SettingsManager.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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());
}
 
Example 11
Source File: NeembuuUploader.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
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);
    }
}
 
Example 12
Source File: SysTrayPlugin.java    From Spark with Apache License 2.0 5 votes vote down vote up
@Override
public void shutdown() {
	if (SystemTray.isSupported()) {
		SystemTray tray = SystemTray.getSystemTray();
		tray.remove(trayIcon);
	}
	ChatManager.getInstance().removeChatMessageHandler(chatMessageHandler);
}
 
Example 13
Source File: SwingUtil.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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;
}
 
Example 14
Source File: SysTray.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
synchronized void initialize() {
    if (SystemTray.isSupported()) {
        mainWindow = WindowManager.getDefault().getMainWindow();
        mainWindowListener = new MainWindowListener();

        lastWindowState = mainWindow.getExtendedState();

        loadSettings();

        if (!hideTrayIcon) showTrayIcon();
        mainWindow.addWindowStateListener(mainWindowListener);
    }
}
 
Example 15
Source File: UpdatePopupMenu.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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");
    }
}
 
Example 16
Source File: OSTrayNotifier.java    From MtgDesktopCompanion with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean isEnable() {
	return SystemTray.isSupported();
}
 
Example 17
Source File: NotificationsHandler.java    From rscplus with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Displays a notification, playing sound if it is enabled
 *
 * <p>TODO: Add fade-in and fade-out or slide-in and slide-out animations
 *
 * @param title The title of the notification
 * @param text Text message of the notification
 */
public static void displayNotification(final String title, String text, String urgency) {
  // Remove color/formatting codes
  final String sanitizedText =
      text.replaceAll("@...@", "").replaceAll("~...~", "").replaceAll("\\\\", "\\\\\\\\");

  if (Settings.USE_SYSTEM_NOTIFICATIONS.get(Settings.currentProfile)
      && !System.getProperty("os.name").contains("Windows")) {
    if (!hasNotifySend) {
      Client.displayMessage(
          "@red@You have to install notify-send for native system notifications!",
          Client.CHAT_QUEST);
      Client.displayMessage(
          "@red@(restart rsc+ if you have installed notify-send)", Client.CHAT_QUEST);
    } else {
      try {
        String output =
            execCmd(
                new String[] {
                  "notify-send",
                  "-u",
                  urgency,
                  "-i",
                  "assets/notification_background.png",
                  title,
                  sanitizedText
                });
      } catch (IOException e) {
        Logger.Error("Error while running notify-send binary: " + e.getMessage());
        e.printStackTrace();
      }
    }
  } else if (SwingUtilities.isEventDispatchThread()) {
    if (Settings.USE_SYSTEM_NOTIFICATIONS.get(Settings.currentProfile)
        && SystemTray.isSupported()) {
      // TODO: When you click the system notification, it should focus the game client
      TrayHandler.getTrayIcon().displayMessage(title, sanitizedText, MessageType.NONE);
    } else {
      setNotificationWindowVisible(true);
      notificationTitle.setText(title);
      notificationTextArea.setText(sanitizedText);
      notificationFrame.repaint();
    }
  } else {
    SwingUtilities.invokeLater(
        new Runnable() {

          @Override
          public void run() {
            if (Settings.USE_SYSTEM_NOTIFICATIONS.get(Settings.currentProfile)
                && SystemTray.isSupported()) {
              // TODO: When you click the system notification, it should focus the game client
              TrayHandler.getTrayIcon().displayMessage(title, sanitizedText, MessageType.NONE);
            } else {
              setNotificationWindowVisible(true);
              notificationTitle.setText(title);
              notificationTextArea.setText(sanitizedText);
              notificationFrame.repaint();
            }
          }
        });
  }
  setLastNotifTime(System.currentTimeMillis());
}
 
Example 18
Source File: MainBackEndHolder.java    From Repeat with Apache License 2.0 4 votes vote down vote up
public MainBackEndHolder() {
	config = new Config(this);

	if (!SystemTray.isSupported()) {
		LOGGER.warning("System tray is not supported!");
		trayIcon = null;
	} else {
		trayIcon = new MinimizedFrame(BootStrapResources.TRAY_IMAGE, this);
	}
	logHolder = new LogHolder();

	executor = new ScheduledThreadPoolExecutor(10);
	compilingLanguage = Language.MANUAL_BUILD;

	taskGroups = new ArrayList<>();

	peerServiceClientManager = new RepeatsPeerServiceClientManager();
	coreProvider = new CoreProvider(config, peerServiceClientManager);
	taskInvoker = new TaskInvoker(coreProvider, taskGroups);
	actionExecutor = new ActionExecutor(coreProvider);
	keysManager = new GlobalEventsManager(config, coreProvider, actionExecutor);
	replayConfig = ReplayConfig.of();
	runActionConfig = RunActionConfig.of();
	recorder = new Recorder(coreProvider);

	switchRecord = new UserDefinedAction() {
		@Override
		public void action(Core controller) throws InterruptedException {
			switchRecord();
		}
	};

	switchReplay = new UserDefinedAction() {
		@Override
		public void action(Core controller) throws InterruptedException {
			switchReplay();
		}
	};

	switchReplayCompiled = new UserDefinedAction() {
		@Override
		public void action(Core controller) throws InterruptedException {
			switchRunningCompiledAction();
		}
	};

	TaskProcessorManager.setProcessorIdentifyCallback(new Function<Language, Void>(){
		@Override
		public Void apply(Language language) {
			recompiledNativeTasks(language);
			return null;
		}
	});
}
 
Example 19
Source File: MainFrame.java    From scelight with Apache License 2.0 4 votes vote down vote up
/**
 * Installs a system tray icon.
 */
private void installTrayIcon() {
	if ( !SystemTray.isSupported() )
		return;
	
	final TrayIcon trayIcon = new TrayIcon( Icons.MY_APP_ICON.get().getImage(), Consts.APP_NAME_FULL + " is running." );
	trayIcon.setImageAutoSize( true );
	
	try {
		SystemTray.getSystemTray().add( trayIcon );
		
		this.trayIcon = trayIcon;
		
		trayIcon.addActionListener( Actions.SHOW_MAIN_FRAME );
		
		final PopupMenu popup = new PopupMenu();
		final MenuItem restoreMenuItem = new MenuItem( "Show Main Window" );
		restoreMenuItem.addActionListener( Actions.SHOW_MAIN_FRAME );
		popup.add( restoreMenuItem );
		final MenuItem hideMenuItem = new MenuItem( "Hide Main Window" );
		hideMenuItem.addActionListener( Actions.MINIMIZE_TO_TRAY );
		popup.add( hideMenuItem );
		popup.addSeparator();
		final MenuItem restoreDefPosMenuItem = new MenuItem( "Restore Main Window to defaults" );
		restoreDefPosMenuItem.addActionListener( new ActionAdapter() {
			@Override
			public void actionPerformed( final ActionEvent e ) {
				// First ensure it's visible and active:
				Actions.SHOW_MAIN_FRAME.actionPerformed( null );
				// And the default position:
				Actions.RESTORE_DEF_WIN_POSITION.actionPerformed( null );
			}
		} );
		popup.add( restoreDefPosMenuItem );
		popup.addSeparator();
		final MenuItem exitMenuItem = new MenuItem( "Exit" );
		exitMenuItem.addActionListener( Actions.EXIT );
		popup.add( exitMenuItem );
		trayIcon.setPopupMenu( popup );
		
		Actions.MINIMIZE_TO_TRAY.setEnabled( true );
	} catch ( final AWTException ae ) {
		Env.LOGGER.debug( "Failed to install tray icon!", ae );
	}
}
 
Example 20
Source File: TrayIconEventModifiersTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
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 {
        if (System.getProperty("os.name").toLowerCase().startsWith("win"))
            System.err.println("Test can fail if the icon hides to a tray icons pool" +
                    "in Windows 7, which is behavior by default.\n" +
                    "Set \"Right mouse click\" -> \"Customize notification icons\" -> " +
                    "\"Always show all icons and notifications on the taskbar\" true " +
                    "to avoid this problem. Or change behavior only for Java SE tray " +
                    "icon and rerun test.");

        System.out.println(System.getProperty("os.arch"));
        if (System.getProperty("os.name").indexOf("Sun") != -1 &&
                System.getProperty("os.arch").indexOf("sparc") != -1) {
            keyTypes = new int[]{
                    KeyEvent.VK_SHIFT,
                    KeyEvent.VK_CONTROL,
                    KeyEvent.VK_META
            };

            keyNames = new String[]{
                    "SHIFT",
                    "CONTROL",
                    "META"
            };
            keyMasks = new int[]{
                    KeyEvent.SHIFT_DOWN_MASK,
                    KeyEvent.CTRL_DOWN_MASK,
                    KeyEvent.META_DOWN_MASK
            };
        }

        if (SystemTrayIconHelper.isOel7()) {
            System.out.println("OEL 7 doesn't support click modifiers in " +
                    "systray. Skipped");
            return;
        }

        new TrayIconEventModifiersTest().doTest();
    }
}