Minimize + SytemTray

3

People are wanting to click to minimize the program, the icon is next to the clock. I created a button that does this action. I confess that I did not do it, but the author helped me a lot.

This is code I am using on the button. I wish I could do the same by miming the program to stay by the clock without having to click the button I created.

Thank you in advance!

if (SystemTray.isSupported()) {
    final SystemTray systemTray = SystemTray.getSystemTray();
    final TrayIcon trayIcon = new TrayIcon(new ImageIcon(icoPath, "omt").getImage(), "QuickStage");
    trayIcon.setImageAutoSize(true);// Autosize icon base on space

    // Mouse
    MouseAdapter mouseAdapter = new MouseAdapter() {

        // Exibir
        @Override
        public void mouseClicked(MouseEvent e) {
            systemTray.remove(trayIcon);
            main.this.setVisible(true);
        }
    };

    // Ocultar
    trayIcon.addMouseListener(mouseAdapter);
    try {
        systemTray.add(trayIcon);
        main.this.setVisible(false);
        trayIcon.displayMessage("Aviso!", "QuickStage continua em execução...", TrayIcon.MessageType.INFO);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
    
asked by anonymous 30.03.2015 / 03:06

1 answer

6

The answer is already in your code. To get easier, we'll rearrange it:

public void moveToTray() {
    if (!SystemTray.isSupported()) return;
    final SystemTray systemTray = SystemTray.getSystemTray();
    final TrayIcon trayIcon = new TrayIcon(new ImageIcon(icoPath, "omt").getImage(), "QuickStage");
    trayIcon.setImageAutoSize(true);// Autosize icon base on space

    // Mouse
    MouseAdapter mouseAdapter = new MouseAdapter() {

        // Exibir
        @Override
        public void mouseClicked(MouseEvent e) {
            systemTray.remove(trayIcon);
            main.this.setVisible(true);
        }
    };

    // Ocultar
    trayIcon.addMouseListener(mouseAdapter);
    try {
        systemTray.add(trayIcon);
        main.this.setVisible(false);
        trayIcon.displayMessage("Aviso!", "QuickStage continua em execução...", TrayIcon.MessageType.INFO);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

With this, just call the moveToTray() method whenever you want to minimize the program in tray , including the code of your button:

botao.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        moveToTray();
    }
});

Or, if you have java 8:

botao.addActionListener(e -> moveToTray());
    
30.03.2015 / 03:36