Example usage for java.awt TrayIcon TrayIcon

List of usage examples for java.awt TrayIcon TrayIcon

Introduction

In this page you can find the example usage for java.awt TrayIcon TrayIcon.

Prototype

public TrayIcon(Image image) 

Source Link

Document

Creates a TrayIcon with the specified image.

Usage

From source file:de.mirkosertic.desktopsearch.DesktopSearch.java

@Override
public void start(Stage aStage) throws Exception {

    // This is our base directory
    File theBaseDirectory = new File(SystemUtils.getUserHome(), "FreeSearchIndexDir");
    theBaseDirectory.mkdirs();//from   ww w  . ja v  a 2  s.  com

    configurationManager = new ConfigurationManager(theBaseDirectory);

    Notifier theNotifier = new Notifier();

    stage = aStage;

    // Create the known preview processors
    PreviewProcessor thePreviewProcessor = new PreviewProcessor();

    try {
        // Boot the search backend and set it up for listening to configuration changes
        backend = new Backend(theNotifier, configurationManager.getConfiguration(), thePreviewProcessor);
        configurationManager.addChangeListener(backend);

        // Boot embedded JSP container
        embeddedWebServer = new FrontendEmbeddedWebServer(aStage, backend, thePreviewProcessor,
                configurationManager);

        embeddedWebServer.start();
    } catch (BindException | LockReleaseFailedException | LockObtainFailedException e) {
        // In this case, there is already an instance of DesktopSearch running
        // Inform the instance to bring it to front end terminate the current process.
        URL theURL = new URL(FrontendEmbeddedWebServer.getBringToFrontUrl());
        // Retrieve the content, but it can be safely ignored
        // There must only be the get request
        Object theContent = theURL.getContent();

        // Terminate the JVM. The window of the running instance is visible now.
        System.exit(0);
    }

    aStage.setTitle("Free Desktop Search");
    aStage.setWidth(800);
    aStage.setHeight(600);
    aStage.initStyle(StageStyle.TRANSPARENT);

    FXMLLoader theLoader = new FXMLLoader(getClass().getResource("/scenes/mainscreen.fxml"));
    AnchorPane theMainScene = theLoader.load();

    final DesktopSearchController theController = theLoader.getController();
    theController.configure(this, backend, FrontendEmbeddedWebServer.getSearchUrl(), stage.getOwner());

    Undecorator theUndecorator = new Undecorator(stage, theMainScene);
    theUndecorator.getStylesheets().add("/skin/undecorator.css");

    Scene theScene = new Scene(theUndecorator);

    // Hacky, but works...
    theUndecorator.setStyle("-fx-background-color: rgba(0, 0, 0, 0);");

    theScene.setFill(Color.TRANSPARENT);
    aStage.setScene(theScene);

    aStage.getIcons().add(new Image(getClass().getResourceAsStream("/fds.png")));

    if (SystemTray.isSupported()) {
        Platform.setImplicitExit(false);
        SystemTray theTray = SystemTray.getSystemTray();

        // We need to reformat the icon according to the current tray icon dimensions
        // this depends on the underlying OS
        java.awt.Image theTrayIconImage = Toolkit.getDefaultToolkit()
                .getImage(getClass().getResource("/fds_small.png"));
        int trayIconWidth = new TrayIcon(theTrayIconImage).getSize().width;
        TrayIcon theTrayIcon = new TrayIcon(
                theTrayIconImage.getScaledInstance(trayIconWidth, -1, java.awt.Image.SCALE_SMOOTH),
                "Free Desktop Search");
        theTrayIcon.setImageAutoSize(true);
        theTrayIcon.setToolTip("FXDesktopSearch");
        theTrayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    Platform.runLater(() -> {
                        if (stage.isIconified()) {
                            stage.setIconified(false);
                        }
                        stage.show();
                        stage.toFront();
                    });
                }
            }
        });
        theTray.add(theTrayIcon);

        aStage.setOnCloseRequest(aEvent -> stage.hide());
    } else {

        aStage.setOnCloseRequest(aEvent -> shutdown());
    }

    aStage.setMaximized(true);
    aStage.show();
}

From source file:zxmax.tools.timerreview.Main.java

private TrayIcon getTrayIcon() throws AWTException {
    final TrayIcon trayIcon = new TrayIcon(
            createImage("images/bulb.gif", I18N.getLabel(getClass(), "tray.icon.description")));

    final SystemTray tray = SystemTray.getSystemTray();
    tray.add(trayIcon);//ww  w  .j  a  v  a 2  s  .c o m

    final PopupMenu popup = new PopupMenu();
    trayIcon.setPopupMenu(popup);

    /*
     * Serve per aprire il popup sulla tray icon con il tasto sx del mouse.
     * Il problema  chiuderla/nasconderla ...
     */
    // trayIcon.addMouseListener(new TrayIconMouseAdapter(popup));

    final MenuItem exitItem = new MenuItem(I18N.getLabel(getClass(), "exit"));
    final MenuItem newTimerItem = new MenuItem(I18N.getLabel(getClass(), "new.timer"));
    newTimerItem.setEnabled(false);
    final MenuItem infoItem = new MenuItem(I18N.getLabel(getClass(), "info"));
    popup.add(exitItem);
    popup.add(newTimerItem);
    popup.add(infoItem);

    exitItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            tray.remove(trayIcon);
            System.exit(0);
        }
    });

    newTimerItem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            StartTimerWindow timer = new StartTimerWindow();
            timer.setVisible(true);
        }
    });

    infoItem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            InfoWindow infoWindow = new InfoWindow();
            infoWindow.setVisible(true);
            infoWindow.createBufferStrategy(1);
        }
    });
    return trayIcon;
}

From source file:de.mycrobase.jcloudapp.Main.java

public void run() {
    if (!SystemTray.isSupported()) {
        showErrorDialog("SystemTray is unsupported!");
        exit();/*w  w  w. j  a  v a 2s . c o m*/
    }

    icon = new TrayIcon(ImageNormal);
    icon.setImageAutoSize(true);
    icon.setToolTip("JCloudApp");
    icon.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (!working) {
                working = true;
                doUploadClipboard();
                working = false;
            }
        }
    });

    MenuItem screen = new MenuItem("Take Screenshot");
    screen.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (!working) {
                working = true;
                doScreenshot();
                working = false;
            }
        }
    });

    MenuItem uploadClip = new MenuItem("Upload from Clipboard");
    uploadClip.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (!working) {
                working = true;
                doUploadClipboard();
                working = false;
            }
        }
    });

    MenuItem upload = new MenuItem("Upload File...");
    upload.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (!working) {
                working = true;
                doUploadFile();
                working = false;
            }
        }
    });

    MenuItem about = new MenuItem("About");
    about.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            doAbout();
        }
    });

    MenuItem quit = new MenuItem("Quit");
    quit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            doQuit();
        }
    });

    PopupMenu popupMenu = new PopupMenu();
    popupMenu.add(screen);
    popupMenu.add(uploadClip);
    popupMenu.add(upload);
    popupMenu.add(about);
    popupMenu.addSeparator();
    popupMenu.add(quit);
    icon.setPopupMenu(popupMenu);

    try {
        SystemTray.getSystemTray().add(icon);
    } catch (AWTException ex) {
        showErrorDialog("No SystemTray found!\n" + ex);
        exit();
    }
}

From source file:MonitorSaurausRex.MainMenu.java

private static void createAndShowGUI() {
    //Check the SystemTray support
    if (!SystemTray.isSupported()) {
        System.out.println("SystemTray is not supported");
        return;/*from   www .  j av a2s . co m*/
    }
    final PopupMenu popup = new PopupMenu();
    final TrayIcon trayIcon = new TrayIcon(createImage("Logo.png", "tray icon"));
    final SystemTray tray = SystemTray.getSystemTray();
    trayIcon.setImageAutoSize(true);
    // Create a popup menu components
    MenuItem aboutItem = new MenuItem("About");
    CheckboxMenuItem cb1 = new CheckboxMenuItem("Menu");
    CheckboxMenuItem cb2 = new CheckboxMenuItem("Quarantine!");
    Menu displayMenu = new Menu("Actions");
    MenuItem errorItem = new MenuItem("Cut Connections");
    MenuItem warningItem = new MenuItem("Send Reports");
    MenuItem infoItem = new MenuItem("Kill Processes");
    MenuItem exitItem = new MenuItem("Exit");

    //Add components to popup menu
    popup.add(aboutItem);
    popup.addSeparator();
    popup.add(cb1);
    popup.add(cb2);
    popup.addSeparator();
    popup.add(displayMenu);
    displayMenu.add(errorItem);
    displayMenu.add(warningItem);
    displayMenu.add(infoItem);
    popup.add(exitItem);

    trayIcon.setPopupMenu(popup);

    try {
        tray.add(trayIcon);
    } catch (AWTException e) {
        System.out.println("TrayIcon could not be added.");
        return;
    }

    trayIcon.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "This dialog box is run from System Tray");
        }
    });

    aboutItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null,
                    "MonitorSaurausRex, Designed for sec203 group project. The program was designed to be piece of software to combat Ransomware"
                            + " in a corparate enviroment. The Project was created by Luke Barlow, Dayan Patel, Rob Shire and Sian Skiggs.");
        }
    });

    cb1.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            int cb1Id = e.getStateChange();
            trayIcon.setImageAutoSize(true);
            if (cb1Id == ItemEvent.SELECTED) {
                trayIcon.setImageAutoSize(true);
            } else {
                trayIcon.setImageAutoSize(true);
            }
        }
    });

    cb2.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            int cb2Id = e.getStateChange();
            if (cb2Id == ItemEvent.SELECTED) {
                trayIcon.setToolTip("Sun TrayIcon");
            } else {
                trayIcon.setToolTip(null);
            }
        }
    });

    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            MenuItem item = (MenuItem) e.getSource();
            //TrayIcon.MessageType type = null;
            System.out.println(item.getLabel());
            if ("Error".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.ERROR;
                trayIcon.displayMessage("Sun TrayIcon Demo", "This is an error message",
                        TrayIcon.MessageType.ERROR);

            } else if ("Warning".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.WARNING;
                trayIcon.displayMessage("Sun TrayIcon Demo", "This is a warning message",
                        TrayIcon.MessageType.WARNING);

            } else if ("Info".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.INFO;
                trayIcon.displayMessage("Sun TrayIcon Demo", "This is an info message",
                        TrayIcon.MessageType.INFO);

            } else if ("None".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.NONE;
                trayIcon.displayMessage("Sun TrayIcon Demo", "This is an ordinary message",
                        TrayIcon.MessageType.NONE);
            }
        }
    };

    errorItem.addActionListener(listener);
    warningItem.addActionListener(listener);
    infoItem.addActionListener(listener);

    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            tray.remove(trayIcon);
            System.exit(0);
        }
    });
}

From source file:neembuu.uploader.NeembuuUploader.java

private void setUpTrayIcon() {
    if (SystemTray.isSupported()) {
        //trayIcon.setImageAutoSize(true); It renders the icon very poorly.
        //So we render the icon ourselves with smooth settings.
        {//from w ww.  j av  a  2 s .  c  o m
            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);
            }
        });
    }
}

From source file:jatoo.app.App.java

public App(final String title) {

    this.title = title;

    ////from  ww w. j  a v a2s. c  om
    // load properties

    properties = new AppProperties(new File(getWorkingDirectory(), "app.properties"));
    properties.loadSilently();

    //
    // resources

    texts = new ResourcesTexts(getClass(), new ResourcesTexts(App.class));
    images = new ResourcesImages(getClass(), new ResourcesImages(App.class));

    //
    // create & initialize the window

    if (isDialog()) {

        window = new JDialog((Frame) null, getTitle());

        if (isUndecorated()) {
            ((JDialog) window).setUndecorated(true);
            ((JDialog) window).setBackground(new Color(0, 0, 0, 0));
        }

        ((JDialog) window).setResizable(isResizable());
    }

    else {

        window = new JFrame(getTitle());

        if (isUndecorated()) {
            ((JFrame) window).setUndecorated(true);
            ((JFrame) window).setBackground(new Color(0, 0, 0, 0));
        }

        ((JFrame) window).setResizable(isResizable());
    }

    window.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(final WindowEvent e) {
            System.exit(0);
        }

        @Override
        public void windowIconified(final WindowEvent e) {
            if (isHideWhenMinimized()) {
                hide();
            }
        }
    });

    //
    // set icon images
    // is either all icons from initializer package
    // or all icons from app package

    List<Image> windowIconImages = new ArrayList<>();
    String[] windowIconImagesNames = new String[] { "016", "020", "022", "024", "032", "048", "064", "128",
            "256", "512" };

    for (String size : windowIconImagesNames) {
        try {
            windowIconImages.add(new ImageIcon(getClass().getResource("app-icon-" + size + ".png")).getImage());
        } catch (Exception e) {
        }
    }

    if (windowIconImages.size() == 0) {

        for (String size : windowIconImagesNames) {
            try {
                windowIconImages
                        .add(new ImageIcon(App.class.getResource("app-icon-" + size + ".png")).getImage());
            } catch (Exception e) {
            }
        }
    }

    window.setIconImages(windowIconImages);

    //
    // this is the place for to call init method
    // after all local components are created
    // from now (after init) is only configuration

    init();

    //
    // set content pane ( and ansure transparency )

    JComponent contentPane = getContentPane();
    contentPane.setOpaque(false);

    ((RootPaneContainer) window).setContentPane(contentPane);

    //
    // pack the window right after the set of the content pane

    window.pack();

    //
    // center window (as default in case restore fails)
    // and try to restore the last location

    window.setLocationRelativeTo(null);
    window.setLocation(properties.getLocation(window.getLocation()));

    if (!isUndecorated()) {

        if (properties.getLastUndecorated(isUndecorated()) == isUndecorated()) {

            if (isResizable() && isSizePersistent()) {

                final String currentLookAndFeel = String.valueOf(UIManager.getLookAndFeel());

                if (properties.getLastLookAndFeel(currentLookAndFeel).equals(currentLookAndFeel)) {
                    window.setSize(properties.getSize(window.getSize()));
                }
            }
        }
    }

    //
    // fix location if out of screen

    Rectangle intersection = window.getGraphicsConfiguration().getBounds().intersection(window.getBounds());

    if ((intersection.width < window.getWidth() * 1 / 2)
            || (intersection.height < window.getHeight() * 1 / 2)) {
        UIUtils.setWindowLocationRelativeToScreen(window);
    }

    //
    // restore some properties

    setAlwaysOnTop(properties.isAlwaysOnTop());
    setHideWhenMinimized(properties.isHideWhenMinimized());
    setTransparency(properties.getTransparency(transparency));

    //
    // null is also a good value for margins glue gaps (is [0,0,0,0])

    Insets marginsGlueGaps = getMarginsGlueGaps();
    if (marginsGlueGaps == null) {
        marginsGlueGaps = new Insets(0, 0, 0, 0);
    }

    //
    // glue to margins on Ctrl + ARROWS

    if (isGlueToMarginsOnCtrlArrows()) {

        UIUtils.setActionForCtrlDownKeyStroke(((RootPaneContainer) window).getRootPane(),
                new ActionGlueMarginBottom(window, marginsGlueGaps.bottom));
        UIUtils.setActionForCtrlLeftKeyStroke(((RootPaneContainer) window).getRootPane(),
                new ActionGlueMarginLeft(window, marginsGlueGaps.left));
        UIUtils.setActionForCtrlRightKeyStroke(((RootPaneContainer) window).getRootPane(),
                new ActionGlueMarginRight(window, marginsGlueGaps.right));
        UIUtils.setActionForCtrlUpKeyStroke(((RootPaneContainer) window).getRootPane(),
                new ActionGlueMarginTop(window, marginsGlueGaps.top));
    }

    //
    // drag to move ( when provided component is not null )

    JComponent dragToMoveComponent = getDragToMoveComponent();

    if (dragToMoveComponent != null) {

        //
        // move the window by dragging the UI component

        int marginsGlueRange = Math.min(window.getGraphicsConfiguration().getBounds().width,
                window.getGraphicsConfiguration().getBounds().height);
        marginsGlueRange /= 60;
        marginsGlueRange = Math.max(marginsGlueRange, 15);

        UIUtils.forwardDragAsMove(dragToMoveComponent, window, marginsGlueRange, marginsGlueGaps);

        //
        // window popup

        dragToMoveComponent.addMouseListener(new MouseAdapter() {
            public void mouseReleased(final MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    windowPopup = getWindowPopup(e.getLocationOnScreen());
                    windowPopup.setVisible(true);
                }
            }
        });

        //
        // always dispose the popup when window lose the focus

        window.addFocusListener(new FocusAdapter() {
            public void focusLost(final FocusEvent e) {
                if (windowPopup != null) {
                    windowPopup.setVisible(false);
                    windowPopup = null;
                }
            }
        });
    }

    //
    // tray icon

    if (hasTrayIcon()) {

        if (SystemTray.isSupported()) {

            Image trayIconImage = windowIconImages.get(0);
            Dimension trayIconSize = SystemTray.getSystemTray().getTrayIconSize();

            for (Image windowIconImage : windowIconImages) {

                if (Math.abs(trayIconSize.width - windowIconImage.getWidth(null)) < Math
                        .abs(trayIconImage.getWidth(null) - windowIconImage.getWidth(null))) {
                    trayIconImage = windowIconImage;
                }
            }

            final TrayIcon trayIcon = new TrayIcon(trayIconImage);
            trayIcon.setPopupMenu(getTrayIconPopup());

            trayIcon.addMouseListener(new MouseAdapter() {
                public void mouseClicked(final MouseEvent e) {

                    if (SwingUtilities.isLeftMouseButton(e)) {
                        if (e.getClickCount() >= 2) {
                            if (window.isVisible()) {
                                hide();
                            } else {
                                show();
                            }
                        }
                    }
                }
            });

            try {
                SystemTray.getSystemTray().add(trayIcon);
            } catch (AWTException e) {
                logger.error(
                        "unexpected exception trying to add the tray icon ( the desktop system tray is missing? )",
                        e);
            }
        }

        else {
            logger.error("the system tray is not supported on the current platform");
        }
    }

    //
    // hidden or not

    if (properties.isVisible()) {
        window.setVisible(true);
    }

    //
    // close the splash screen
    // if there is one

    try {

        SplashScreen splash = SplashScreen.getSplashScreen();

        if (splash != null) {
            splash.close();
        }
    }

    catch (UnsupportedOperationException e) {
        getLogger().info("splash screen not supported", e);
    }

    //
    // add shutdown hook for #destroy()

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            App.this.destroy();
        }
    });

    //
    // after init

    afterInit();
}

From source file:com.jsystem.j2autoit.AutoItAgent.java

private static void createAndShowGUI() {
    //Check the SystemTray support
    if (!SystemTray.isSupported()) {
        Log.error("SystemTray is not supported\n");
        return;//from   www  .  j a v a2 s  .c o  m
    }
    final PopupMenu popup = new PopupMenu();
    final TrayIcon trayIcon = new TrayIcon(createImage("images/jsystem_ico.gif", "tray icon"));
    final SystemTray tray = SystemTray.getSystemTray();

    // Create a popup menu components
    final MenuItem aboutItem = new MenuItem("About");
    final MenuItem startAgentItem = new MenuItem("Start J2AutoIt Agent");
    final MenuItem stopAgentItem = new MenuItem("Stop J2AutoIt Agent");
    final MenuItem exitItem = new MenuItem("Exit");
    final MenuItem changePortItem = new MenuItem("Setting J2AutoIt Port");
    final MenuItem deleteTemporaryFilesItem = new MenuItem("Delete J2AutoIt Script");
    final MenuItem temporaryHistoryFilesItem = new MenuItem("History Size");
    final MenuItem displayLogFile = new MenuItem("Log");
    final MenuItem forceShutDownTimeOutItem = new MenuItem("Force ShutDown TimeOut");
    final MenuItem writeConfigurationToFile = new MenuItem("Save Configuration To File");
    final CheckboxMenuItem debugModeItem = new CheckboxMenuItem("Debug Mode", isDebug);
    final CheckboxMenuItem forceAutoItShutDownItem = new CheckboxMenuItem("Force AutoIt Script ShutDown",
            isForceAutoItShutDown);
    final CheckboxMenuItem autoDeleteHistoryItem = new CheckboxMenuItem("Auto Delete History",
            isAutoDeleteFiles);
    final CheckboxMenuItem useAutoScreenShot = new CheckboxMenuItem("Auto Screenshot", isUseScreenShot);

    //Add components to popup menu
    popup.add(aboutItem);
    popup.add(writeConfigurationToFile);
    popup.addSeparator();
    popup.add(forceAutoItShutDownItem);
    popup.add(forceShutDownTimeOutItem);
    popup.addSeparator();
    popup.add(debugModeItem);
    popup.add(displayLogFile);
    popup.add(useAutoScreenShot);
    popup.addSeparator();
    popup.add(autoDeleteHistoryItem);
    popup.add(deleteTemporaryFilesItem);
    popup.add(temporaryHistoryFilesItem);
    popup.addSeparator();
    popup.add(changePortItem);
    popup.addSeparator();
    popup.add(startAgentItem);
    popup.add(stopAgentItem);
    popup.addSeparator();
    popup.add(exitItem);

    trayIcon.setToolTip("J2AutoIt Agent");
    trayIcon.setImageAutoSize(true);
    trayIcon.setPopupMenu(popup);
    final DisplayLogFile displayLog = new DisplayLogFile();
    try {
        tray.add(trayIcon);
    } catch (AWTException e) {
        Log.error("TrayIcon could not be added.\n");
        return;
    }

    trayIcon.addMouseListener(new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent e) {
        }

        @Override
        public void mouseEntered(MouseEvent e) {
        }

        @Override
        public void mouseExited(MouseEvent e) {
        }

        @Override
        public void mousePressed(MouseEvent e) {
            startAgentItem.setEnabled(!serverState);
            stopAgentItem.setEnabled(serverState);
            deleteTemporaryFilesItem.setEnabled(isDebug && HistoryFile.containEntries());
            autoDeleteHistoryItem.setEnabled(isDebug);
            temporaryHistoryFilesItem.setEnabled(isDebug && isAutoDeleteFiles);
            displayLogFile.setEnabled(isDebug);
            forceShutDownTimeOutItem.setEnabled(isForceAutoItShutDown);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
        }
    });

    writeConfigurationToFile.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            AutoItProperties.DEBUG_MODE_KEY.setValue(isDebug.toString());
            AutoItProperties.AUTO_DELETE_TEMPORARY_SCRIPT_FILE_KEY.setValue(isAutoDeleteFiles.toString());
            AutoItProperties.AUTO_IT_SCRIPT_HISTORY_SIZE_KEY.setValue(DEFAULT_HistorySize.toString());
            AutoItProperties.FORCE_AUTO_IT_PROCESS_SHUTDOWN_KEY.setValue(isForceAutoItShutDown.toString());
            AutoItProperties.AGENT_PORT_KEY.setValue(webServicePort.toString());
            AutoItProperties.SERVER_UP_ON_INIT_KEY.setValue(serverState.toString());
            if (!AutoItProperties.savePropertiesFileSafely()) {
                Log.error("Fail to save properties file");
            }
        }
    });

    debugModeItem.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            isDebug = (e.getStateChange() == ItemEvent.SELECTED);
            deleteTemporaryFilesItem.setEnabled(isDebug && HistoryFile.containEntries());
            Log.infoLog("Keeping the temp file is " + (isDebug ? "en" : "dis") + "able\n");
            trayIcon.displayMessage((isDebug ? "Debug" : "Normal") + " Mode",
                    "The system will " + (isDebug ? "not " : "") + "delete \nthe temporary autoIt scripts."
                            + (isDebug ? "\nSee log file for more info." : ""),
                    MessageType.INFO);
        }
    });

    useAutoScreenShot.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            isUseScreenShot = (e.getStateChange() == ItemEvent.SELECTED);
            Log.infoLog("Auto screenshot is " + (isUseScreenShot ? "" : "in") + "active\n");
        }
    });

    forceAutoItShutDownItem.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            isForceAutoItShutDown = (e.getStateChange() == ItemEvent.SELECTED);
            Log.infoLog((isForceAutoItShutDown ? "Force" : "Soft") + " AutoIt Script ShutDown\n");
            trayIcon.displayMessage("AutoIt Script Termination",
                    (isForceAutoItShutDown ? "Hard shutdown" : "Soft shutdown"), MessageType.INFO);
        }
    });

    autoDeleteHistoryItem.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            isAutoDeleteFiles = (e.getStateChange() == ItemEvent.SELECTED);
            Log.infoLog((isAutoDeleteFiles ? "Auto" : "Manual") + " AutoIt Script Deletion\n");
            trayIcon.displayMessage("AutoIt Script Deletion", (isAutoDeleteFiles ? "Auto" : "Manual") + " Mode",
                    MessageType.INFO);
            if (isAutoDeleteFiles) {
                HistoryFile.init();
            } else {
                HistoryFile.close();
            }
        }
    });

    forceShutDownTimeOutItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            String timeOutAsString = JOptionPane.showInputDialog(
                    "Please Insert Force ShutDown TimeOut (in seconds)",
                    String.valueOf(shutDownTimeOut / 1000));
            try {
                shutDownTimeOut = 1000 * Long.parseLong(timeOutAsString);
            } catch (Exception e2) {
            }
            Log.infoLog("Setting the force shutdown time out to : " + (shutDownTimeOut / 1000) + " seconds.\n");
        }
    });

    displayLogFile.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            try {
                displayLog.reBuild(Log.getCurrentLogs());
                displayLog.actionPerformed(actionEvent);
            } catch (Exception e2) {
            }
        }
    });

    temporaryHistoryFilesItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            String historySize = JOptionPane.showInputDialog("Please Insert History AutoIt Script Files",
                    String.valueOf(HistoryFile.getHistory_Size()));
            try {
                int temp = Integer.parseInt(historySize);
                if (temp > 0) {
                    if (HistoryFile.getHistory_Size() != temp) {
                        HistoryFile.setHistory_Size(temp);
                        Log.infoLog("The history files size is " + historySize + NEW_LINE);
                    }
                } else {
                    Log.warning("Illegal History Size: " + historySize + NEW_LINE);
                }
            } catch (Exception exception) {
                Log.throwableLog(exception.getMessage(), exception);
            }
        }
    });

    deleteTemporaryFilesItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            HistoryFile.forceDeleteAll();
        }
    });

    startAgentItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            runWebServer();
        }
    });

    stopAgentItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            shutDownWebServer();
        }
    });

    aboutItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            JOptionPane.showMessageDialog(null, "J2AutoIt Agent By JSystem And Aqua Software");
        }
    });

    changePortItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            String portAsString = JOptionPane.showInputDialog("Please Insert new Port",
                    String.valueOf(webServicePort));
            if (portAsString != null) {
                try {
                    int temp = Integer.parseInt(portAsString);
                    if (temp > 1000) {
                        if (temp != webServicePort) {
                            webServicePort = temp;
                            shutDownWebServer();
                            startAutoItWebServer(webServicePort);
                            runWebServer();
                        }
                    } else {
                        Log.warning("Port number should be greater then 1000\n");
                    }
                } catch (Exception exception) {
                    Log.error("Illegal port number\n");
                    return;
                }
            }
        }
    });

    exitItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            tray.remove(trayIcon);
            shutDownWebServer();
            Log.info("Exiting from J2AutoIt Agent\n");
            System.exit(0);
        }
    });
}

From source file:net.sourceforge.entrainer.gui.EntrainerFX.java

private void addSystemTrayIcon() {
    if (!SystemTray.isSupported())
        return;//  ww w .ja v a 2s.  co  m

    TrayIcon icon = new TrayIcon(this.icon.getImage());
    icon.setPopupMenu(getTrayIconPopup());
    icon.setToolTip("EntrainerFX");

    try {
        SystemTray.getSystemTray().add(icon);
    } catch (AWTException e) {
        GuiUtil.handleProblem(e);
    }
}

From source file:org.gtdfree.GTDFree.java

protected TrayIcon getTrayIcon() {
    if (trayIcon == null) {
        if (ApplicationHelper.isGTKLaF()) {
            trayIcon = new TrayIcon(ApplicationHelper.loadImage(ApplicationHelper.icon_name_large_tray_splash));
        } else {//w  ww .  j a v a2s  .com
            trayIcon = new TrayIcon(ApplicationHelper.loadImage(ApplicationHelper.icon_name_small_tray_splash));
        }

        trayIcon.setImageAutoSize(true);
        trayIcon.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    trayIconPopup.setVisible(false);
                    if (getJFrame().isVisible()) {
                        getJFrame().setVisible(false);
                    } else {
                        pushVisible();
                    }
                } else {
                    if (trayIconPopup.isVisible()) {
                        trayIconPopup.setVisible(false);
                    } else {
                        Point p = new Point(e.getPoint());
                        /*
                         * Disabled, because we are anyway doing things like rollover,
                         * which are probably done by Frame.
                        if (getJFrame().isShowing()) {
                           SwingUtilities.convertPointFromScreen(p, getJFrame());
                           trayIconPopup.show(getJFrame(), p.x, p.y);
                        } else {
                        }*/
                        trayIconPopup.show(null, p.x, p.y);
                    }
                }
            }
        });
        trayIcon.setToolTip("GTD-Free - " + Messages.getString("GTDFree.Tray.desc")); //$NON-NLS-1$ //$NON-NLS-2$

        /*
         * Necessary only when popup is showing with null window. Hides popup.
         */
        MouseListener hideMe = new MouseAdapter() {
            @Override
            public void mouseExited(MouseEvent e) {
                if (e.getComponent() instanceof JMenuItem) {
                    JMenuItem jm = (JMenuItem) e.getComponent();
                    jm.getModel().setRollover(false);
                    jm.getModel().setArmed(false);
                    jm.repaint();
                }

                Point p = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), trayIconPopup);
                //System.out.println(p.x+" "+p.y+" "+trayIconPopup.getWidth()+" "+trayIconPopup.getHeight());
                if (p.x < 0 || p.x >= trayIconPopup.getWidth() || p.y < 0 || p.y >= trayIconPopup.getHeight()) {
                    trayIconPopup.setVisible(false);
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                if (e.getComponent() instanceof JMenuItem) {
                    JMenuItem jm = (JMenuItem) e.getComponent();
                    jm.getModel().setRollover(true);
                    jm.getModel().setArmed(true);
                    jm.repaint();
                }
            }
        };

        trayIconPopup = new JPopupMenu();
        trayIconPopup.addMouseListener(hideMe);

        JMenuItem mi = new JMenuItem(Messages.getString("GTDFree.Tray.Drop")); //$NON-NLS-1$
        mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_small_collecting));
        mi.setToolTipText(Messages.getString("GTDFree.Tray.Drop.desc")); //$NON-NLS-1$
        mi.addMouseListener(hideMe);

        /*
         * Workaround for tray, if JFrame is showing, then mouse click is not fired
         */
        mi.addMouseListener(new MouseAdapter() {
            private boolean click = false;

            @Override
            public void mousePressed(MouseEvent e) {
                click = true;
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (click) {
                    click = false;
                    doMouseClicked(e);
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                click = false;
            }

            private void doMouseClicked(MouseEvent e) {
                trayIconPopup.setVisible(false);
                Clipboard c = null;
                if (e.getButton() == MouseEvent.BUTTON1) {
                    c = Toolkit.getDefaultToolkit().getSystemClipboard();
                } else if (e.getButton() == MouseEvent.BUTTON2) {
                    c = Toolkit.getDefaultToolkit().getSystemSelection();
                } else {
                    return;
                }
                try {
                    Object o = c.getData(DataFlavor.stringFlavor);
                    if (o != null) {
                        getEngine().getGTDModel().collectAction(o.toString());
                    }
                    flashMessage(Messages.getString("GTDFree.Tray.Collect.ok"), e.getLocationOnScreen()); //$NON-NLS-1$
                } catch (Exception e1) {
                    Logger.getLogger(this.getClass()).debug("Internal error.", e1); //$NON-NLS-1$
                    flashMessage(Messages.getString("GTDFree.Tray.Collect.fail") + e1.getMessage(), //$NON-NLS-1$
                            e.getLocationOnScreen());
                }
            }
        });

        TransferHandler th = new TransferHandler() {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
                return DataFlavor.selectBestTextFlavor(transferFlavors) != null;
            }

            @Override
            public boolean importData(JComponent comp, Transferable t) {
                try {
                    DataFlavor f = DataFlavor.selectBestTextFlavor(t.getTransferDataFlavors());
                    Object o = t.getTransferData(f);
                    if (o != null) {
                        getEngine().getGTDModel().collectAction(o.toString());
                    }
                    return true;
                } catch (UnsupportedFlavorException e) {
                    Logger.getLogger(this.getClass()).debug("Internal error.", e); //$NON-NLS-1$
                } catch (IOException e) {
                    Logger.getLogger(this.getClass()).debug("Internal error.", e); //$NON-NLS-1$
                }
                return false;
            }

        };
        mi.setTransferHandler(th);

        trayIconPopup.add(mi);

        mi = new JMenuItem();
        mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_large_delete));
        mi.setText(Messages.getString("GTDFree.Tray.Hide")); //$NON-NLS-1$
        mi.setToolTipText(Messages.getString("GTDFree.Tray.Hide.desc")); //$NON-NLS-1$
        mi.addMouseListener(hideMe);
        mi.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                trayIconPopup.setVisible(false);
                if (getJFrame().isVisible()) {
                    getJFrame().setVisible(false);
                }
            }
        });
        trayIconPopup.add(mi);

        mi = new JMenuItem();
        mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_small_splash));
        mi.setText(Messages.getString("GTDFree.Tray.Show")); //$NON-NLS-1$
        mi.setToolTipText(Messages.getString("GTDFree.Tray.Show.desc")); //$NON-NLS-1$
        mi.addMouseListener(hideMe);
        mi.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                trayIconPopup.setVisible(false);
                pushVisible();
            }
        });
        trayIconPopup.add(mi);

        mi = new JMenuItem();
        mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_large_exit));
        mi.setText(Messages.getString("GTDFree.Tray.Exit")); //$NON-NLS-1$
        mi.addMouseListener(hideMe);
        mi.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                trayIconPopup.setVisible(false);
                close(false);
            }
        });
        trayIconPopup.add(mi);

    }
    return trayIcon;
}

From source file:de.bwravencl.controllerbuddy.gui.Main.java

private Main() {
    Singleton.start(this, SINGLETON_ID);

    frame = new JFrame();
    frame.addWindowListener(new WindowAdapter() {

        @Override/*from   w w  w.j a v a  2  s . c o m*/
        public void windowClosing(final WindowEvent e) {
            super.windowClosing(e);

            if (showMenuItem != null)
                showMenuItem.setEnabled(true);
        }

        @Override
        public void windowDeiconified(final WindowEvent e) {
            super.windowDeiconified(e);

            if (showMenuItem != null)
                showMenuItem.setEnabled(false);
        }

        @Override
        public void windowIconified(final WindowEvent e) {
            super.windowIconified(e);

            if (showMenuItem != null)
                showMenuItem.setEnabled(true);
        }

        @Override
        public void windowOpened(final WindowEvent e) {
            super.windowOpened(e);

            if (showMenuItem != null)
                showMenuItem.setEnabled(false);
        }

    });

    frame.setBounds(DIALOG_BOUNDS_X, DIALOG_BOUNDS_Y, DIALOG_BOUNDS_WIDTH, DIALOG_BOUNDS_HEIGHT);
    frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);

    final var icons = new ArrayList<Image>();
    for (final var path : ICON_RESOURCE_PATHS) {
        final var icon = new ImageIcon(Main.class.getResource(path));
        icons.add(icon.getImage());
    }
    frame.setIconImages(icons);

    frame.setJMenuBar(menuBar);

    menuBar.add(fileMenu);
    final QuitAction quitAction = new QuitAction();
    fileMenu.add(quitAction);
    menuBar.add(deviceMenu);

    if (windows) {
        menuBar.add(localMenu, 2);

        final var buttonGroupLocalState = new ButtonGroup();
        startLocalRadioButtonMenuItem = new JRadioButtonMenuItem(rb.getString("START_MENU_ITEM"));
        startLocalRadioButtonMenuItem.setAction(new StartLocalAction());
        buttonGroupLocalState.add(startLocalRadioButtonMenuItem);
        localMenu.add(startLocalRadioButtonMenuItem);

        stopLocalRadioButtonMenuItem = new JRadioButtonMenuItem(rb.getString("STOP_MENU_ITEM"));
        stopLocalRadioButtonMenuItem.setAction(new StopLocalAction());
        buttonGroupLocalState.add(stopLocalRadioButtonMenuItem);
        localMenu.add(stopLocalRadioButtonMenuItem);

        menuBar.add(clientMenu);

        final var buttonGroupClientState = new ButtonGroup();

        startClientRadioButtonMenuItem = new JRadioButtonMenuItem(rb.getString("START_MENU_ITEM"));
        startClientRadioButtonMenuItem.setAction(new StartClientAction());
        buttonGroupClientState.add(startClientRadioButtonMenuItem);
        clientMenu.add(startClientRadioButtonMenuItem);

        stopClientRadioButtonMenuItem = new JRadioButtonMenuItem(rb.getString("STOP_MENU_ITEM"));
        stopClientRadioButtonMenuItem.setAction(new StopClientAction());
        buttonGroupClientState.add(stopClientRadioButtonMenuItem);
        clientMenu.add(stopClientRadioButtonMenuItem);
    }

    final var buttonGroupServerState = new ButtonGroup();
    startServerRadioButtonMenuItem = new JRadioButtonMenuItem(rb.getString("START_MENU_ITEM"));
    startServerRadioButtonMenuItem.setAction(new StartServerAction());
    buttonGroupServerState.add(startServerRadioButtonMenuItem);
    serverMenu.add(startServerRadioButtonMenuItem);

    stopServerRadioButtonMenuItem = new JRadioButtonMenuItem(rb.getString("STOP_MENU_ITEM"));
    stopServerRadioButtonMenuItem.setAction(new StopServerAction());
    buttonGroupServerState.add(stopServerRadioButtonMenuItem);
    serverMenu.add(stopServerRadioButtonMenuItem);

    final var helpMenu = new JMenu(rb.getString("HELP_MENU"));
    menuBar.add(helpMenu);
    helpMenu.add(new ShowAboutDialogAction());

    frame.getContentPane().add(tabbedPane);

    settingsPanel = new JPanel();
    settingsPanel.setLayout(new GridBagLayout());

    settingsScrollPane.setViewportView(settingsPanel);
    tabbedPane.addTab(rb.getString("SETTINGS_TAB"), null, settingsScrollPane);

    final var panelGridBagConstraints = new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
            GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 5);

    final var panelFlowLayout = new FlowLayout(FlowLayout.LEADING, 10, 10);

    final var pollIntervalPanel = new JPanel(panelFlowLayout);
    settingsPanel.add(pollIntervalPanel, panelGridBagConstraints);

    final var pollIntervalLabel = new JLabel(rb.getString("POLL_INTERVAL_LABEL"));
    pollIntervalLabel.setPreferredSize(new Dimension(120, 15));
    pollIntervalPanel.add(pollIntervalLabel);

    final var pollIntervalSpinner = new JSpinner(new SpinnerNumberModel(
            preferences.getInt(PREFERENCES_POLL_INTERVAL, OutputThread.DEFAULT_POLL_INTERVAL), 10, 500, 1));
    final JSpinner.DefaultEditor pollIntervalSpinnerEditor = new JSpinner.NumberEditor(pollIntervalSpinner,
            "#");
    ((DefaultFormatter) pollIntervalSpinnerEditor.getTextField().getFormatter()).setCommitsOnValidEdit(true);
    pollIntervalSpinner.setEditor(pollIntervalSpinnerEditor);
    pollIntervalSpinner.addChangeListener(
            e -> preferences.putInt(PREFERENCES_POLL_INTERVAL, (int) ((JSpinner) e.getSource()).getValue()));
    pollIntervalPanel.add(pollIntervalSpinner);

    if (windows) {
        final var vJoyDirectoryPanel = new JPanel(panelFlowLayout);
        settingsPanel.add(vJoyDirectoryPanel, panelGridBagConstraints);

        final var vJoyDirectoryLabel = new JLabel(rb.getString("VJOY_DIRECTORY_LABEL"));
        vJoyDirectoryLabel.setPreferredSize(new Dimension(120, 15));
        vJoyDirectoryPanel.add(vJoyDirectoryLabel);

        vJoyDirectoryLabel1 = new JLabel(
                preferences.get(PREFERENCES_VJOY_DIRECTORY, VJoyOutputThread.getDefaultInstallationPath()));
        vJoyDirectoryPanel.add(vJoyDirectoryLabel1);

        final var vJoyDirectoryButton = new JButton(new ChangeVJoyDirectoryAction());
        vJoyDirectoryPanel.add(vJoyDirectoryButton);

        final var vJoyDevicePanel = new JPanel(panelFlowLayout);
        settingsPanel.add(vJoyDevicePanel, panelGridBagConstraints);

        final var vJoyDeviceLabel = new JLabel(rb.getString("VJOY_DEVICE_LABEL"));
        vJoyDeviceLabel.setPreferredSize(new Dimension(120, 15));
        vJoyDevicePanel.add(vJoyDeviceLabel);

        final var vJoyDeviceSpinner = new JSpinner(new SpinnerNumberModel(
                preferences.getInt(PREFERENCES_VJOY_DEVICE, VJoyOutputThread.DEFAULT_VJOY_DEVICE), 1, 16, 1));
        final JSpinner.DefaultEditor vJoyDeviceSpinnerEditor = new JSpinner.NumberEditor(vJoyDeviceSpinner,
                "#");
        ((DefaultFormatter) vJoyDeviceSpinnerEditor.getTextField().getFormatter()).setCommitsOnValidEdit(true);
        vJoyDeviceSpinner.setEditor(vJoyDeviceSpinnerEditor);
        vJoyDeviceSpinner.addChangeListener(
                e -> preferences.putInt(PREFERENCES_VJOY_DEVICE, (int) ((JSpinner) e.getSource()).getValue()));
        vJoyDevicePanel.add(vJoyDeviceSpinner);

        final var hostPanel = new JPanel(panelFlowLayout);
        settingsPanel.add(hostPanel, panelGridBagConstraints);

        final var hostLabel = new JLabel(rb.getString("HOST_LABEL"));
        hostLabel.setPreferredSize(new Dimension(120, 15));
        hostPanel.add(hostLabel);

        hostTextField = new JTextField(preferences.get(PREFERENCES_HOST, ClientVJoyOutputThread.DEFAULT_HOST),
                10);
        final var setHostAction = new SetHostAction(hostTextField);
        hostTextField.addActionListener(setHostAction);
        hostTextField.addFocusListener(setHostAction);
        hostPanel.add(hostTextField);
    }

    final var portPanel = new JPanel(panelFlowLayout);
    settingsPanel.add(portPanel, panelGridBagConstraints);

    final var portLabel = new JLabel(rb.getString("PORT_LABEL"));
    portLabel.setPreferredSize(new Dimension(120, 15));
    portPanel.add(portLabel);

    final var portSpinner = new JSpinner(new SpinnerNumberModel(
            preferences.getInt(PREFERENCES_PORT, ServerOutputThread.DEFAULT_PORT), 1024, 65535, 1));
    final JSpinner.DefaultEditor portSpinnerEditor = new JSpinner.NumberEditor(portSpinner, "#");
    ((DefaultFormatter) portSpinnerEditor.getTextField().getFormatter()).setCommitsOnValidEdit(true);
    portSpinner.setEditor(portSpinnerEditor);
    portSpinner.addChangeListener(
            e -> preferences.putInt(PREFERENCES_PORT, (int) ((JSpinner) e.getSource()).getValue()));
    portPanel.add(portSpinner);

    final var timeoutPanel = new JPanel(panelFlowLayout);
    settingsPanel.add(timeoutPanel, panelGridBagConstraints);

    final var timeoutLabel = new JLabel(rb.getString("TIMEOUT_LABEL"));
    timeoutLabel.setPreferredSize(new Dimension(120, 15));
    timeoutPanel.add(timeoutLabel);

    final var timeoutSpinner = new JSpinner(new SpinnerNumberModel(
            preferences.getInt(PREFERENCES_TIMEOUT, ServerOutputThread.DEFAULT_TIMEOUT), 10, 60000, 1));
    final JSpinner.DefaultEditor timeoutSpinnerEditor = new JSpinner.NumberEditor(timeoutSpinner, "#");
    ((DefaultFormatter) timeoutSpinnerEditor.getTextField().getFormatter()).setCommitsOnValidEdit(true);
    timeoutSpinner.setEditor(timeoutSpinnerEditor);
    timeoutSpinner.addChangeListener(
            e -> preferences.putInt(PREFERENCES_TIMEOUT, (int) ((JSpinner) e.getSource()).getValue()));
    timeoutPanel.add(timeoutSpinner);

    final var alwaysOnTopSupported = Toolkit.getDefaultToolkit().isAlwaysOnTopSupported();
    if (alwaysOnTopSupported || preferences.getBoolean(PREFERENCES_SHOW_OVERLAY, alwaysOnTopSupported)) {
        final var overlaySettingsPanel = new JPanel(panelFlowLayout);
        settingsPanel.add(overlaySettingsPanel, panelGridBagConstraints);

        final var overlayLabel = new JLabel(rb.getString("OVERLAY_LABEL"));
        overlayLabel.setPreferredSize(new Dimension(120, 15));
        overlaySettingsPanel.add(overlayLabel);

        final var showOverlayCheckBox = new JCheckBox(rb.getString("SHOW_OVERLAY_CHECK_BOX"));
        showOverlayCheckBox.setSelected(preferences.getBoolean(PREFERENCES_SHOW_OVERLAY, true));
        showOverlayCheckBox.addActionListener(e -> {
            final boolean showOverlay = ((JCheckBox) e.getSource()).isSelected();

            preferences.putBoolean(PREFERENCES_SHOW_OVERLAY, showOverlay);
        });
        overlaySettingsPanel.add(showOverlayCheckBox);
    }

    if (windows) {
        if (preferences.getBoolean(PREFERENCES_SHOW_VR_OVERLAY, true)) {
            final var vrOverlaySettingsPanel = new JPanel(panelFlowLayout);
            settingsPanel.add(vrOverlaySettingsPanel, panelGridBagConstraints);

            final var vrOverlayLabel = new JLabel(rb.getString("VR_OVERLAY_LABEL"));
            vrOverlayLabel.setPreferredSize(new Dimension(120, 15));
            vrOverlaySettingsPanel.add(vrOverlayLabel);

            final var showVrOverlayCheckBox = new JCheckBox(rb.getString("SHOW_VR_OVERLAY_CHECK_BOX"));
            showVrOverlayCheckBox.setSelected(preferences.getBoolean(PREFERENCES_SHOW_VR_OVERLAY, true));
            showVrOverlayCheckBox.addActionListener(e -> {
                final var showVrOverlay = ((JCheckBox) e.getSource()).isSelected();

                preferences.putBoolean(PREFERENCES_SHOW_VR_OVERLAY, showVrOverlay);
            });
            vrOverlaySettingsPanel.add(showVrOverlayCheckBox);
        }

        final var preventPowerSaveModeSettingsPanel = new JPanel(panelFlowLayout);
        settingsPanel.add(preventPowerSaveModeSettingsPanel, panelGridBagConstraints);

        final var preventPowerSaveModeLabel = new JLabel(rb.getString("POWER_SAVE_MODE_LABEL"));
        preventPowerSaveModeLabel.setPreferredSize(new Dimension(120, 15));
        preventPowerSaveModeSettingsPanel.add(preventPowerSaveModeLabel);

        final var preventPowerSaveModeCheckBox = new JCheckBox(
                rb.getString("PREVENT_POWER_SAVE_MODE_CHECK_BOX"));
        preventPowerSaveModeCheckBox
                .setSelected(preferences.getBoolean(PREFERENCES_PREVENT_POWER_SAVE_MODE, true));
        preventPowerSaveModeCheckBox.addActionListener(e -> {
            final var preventPowerSaveMode = ((JCheckBox) e.getSource()).isSelected();

            preferences.putBoolean(PREFERENCES_PREVENT_POWER_SAVE_MODE, preventPowerSaveMode);
        });
        preventPowerSaveModeSettingsPanel.add(preventPowerSaveModeCheckBox);
    }

    if (SystemTray.isSupported()) {
        final var popupMenu = new PopupMenu();

        final var showAction = new ShowAction();
        showMenuItem = new MenuItem((String) showAction.getValue(Action.NAME));
        showMenuItem.addActionListener(showAction);
        popupMenu.add(showMenuItem);

        popupMenu.addSeparator();

        final var openMenuItem = new MenuItem((String) openAction.getValue(Action.NAME));
        openMenuItem.addActionListener(openAction);
        popupMenu.add(openMenuItem);

        popupMenu.addSeparator();

        final var quitMenuItem = new MenuItem((String) quitAction.getValue(Action.NAME));
        quitMenuItem.addActionListener(quitAction);
        popupMenu.add(quitMenuItem);

        trayIcon = new TrayIcon(frame.getIconImage());
        trayIcon.addActionListener(showAction);
        trayIcon.setPopupMenu(popupMenu);
        try {
            SystemTray.getSystemTray().add(trayIcon);
        } catch (final AWTException e) {
            log.log(Logger.Level.ERROR, e.getMessage(), e);
        }
    }

    updateTitleAndTooltip();

    settingsPanel.add(Box.createGlue(), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0,
            GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));

    final var outsideBorder = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
    final var insideBorder = BorderFactory.createEmptyBorder(0, 5, 0, 5);
    statusLabel.setBorder(BorderFactory.createCompoundBorder(outsideBorder, insideBorder));
    frame.add(statusLabel, BorderLayout.SOUTH);

    final var glfwInitialized = glfwInit();
    if (!glfwInitialized)
        if (windows)
            JOptionPane.showMessageDialog(frame, rb.getString("COULD_NOT_INITIALIZE_GLFW_DIALOG_TEXT_WINDOWS"),
                    rb.getString("ERROR_DIALOG_TITLE"), JOptionPane.ERROR_MESSAGE);
        else {
            JOptionPane.showMessageDialog(frame, rb.getString("COULD_NOT_INITIALIZE_GLFW_DIALOG_TEXT"),
                    rb.getString("ERROR_DIALOG_TITLE"), JOptionPane.ERROR_MESSAGE);
            quit();
        }

    final var presentJids = new HashSet<Integer>();
    for (var jid = GLFW_JOYSTICK_1; jid <= GLFW_JOYSTICK_LAST; jid++)
        if (glfwJoystickPresent(jid) && glfwJoystickIsGamepad(jid))
            presentJids.add(jid);

    final var lastControllerGuid = preferences.get(PREFERENCES_LAST_CONTROLLER, null);
    for (final var jid : presentJids) {
        final var lastControllerFound = lastControllerGuid != null
                ? lastControllerGuid.equals(glfwGetJoystickGUID(jid))
                : false;

        if (!isSelectedJidValid() || lastControllerFound)
            selectedJid = jid;

        if (lastControllerFound)
            break;
    }

    newProfile();

    onControllersChanged(true);

    glfwSetJoystickCallback(new GLFWJoystickCallback() {

        @Override
        public void invoke(final int jid, final int event) {
            final var disconnected = event == GLFW_DISCONNECTED;
            if (disconnected || glfwJoystickIsGamepad(jid)) {
                if (disconnected && selectedJid == jid)
                    selectedJid = INVALID_JID;

                invokeOnEventDispatchThreadIfRequired(() -> onControllersChanged(false));
            }

        }
    });

    if (glfwInitialized && presentJids.isEmpty()) {
        if (windows)
            JOptionPane.showMessageDialog(frame, rb.getString("NO_CONTROLLER_CONNECTED_DIALOG_TEXT_WINDOWS"),
                    rb.getString("INFORMATION_DIALOG_TITLE"), JOptionPane.INFORMATION_MESSAGE);
        else
            JOptionPane.showMessageDialog(frame, rb.getString("NO_CONTROLLER_CONNECTED_DIALOG_TEXT"),
                    rb.getString("INFORMATION_DIALOG_TITLE"), JOptionPane.INFORMATION_MESSAGE);
    } else {
        final String path = preferences.get(PREFERENCES_LAST_PROFILE, null);
        if (path != null)
            loadProfile(new File(path));
    }
}