mythbu
mythbu

Reputation: 657

Hide a JFrame and display it again through a click on the dock icon

My application has a JFrame and checks every x seconds if something changed. So I would like to hide my JFrame via setVisible(false) on a click on the close button and redisplay it when the icon in the dock (I'm using Mac OS, but it should work the same way with the Windows task bar) is clicked. You know: many applications do this temporary hiding.

Have you got any ideas how to do this? How to listen on these click events?

Upvotes: 1

Views: 2361

Answers (2)

nhaggen
nhaggen

Reputation: 443

Use the com.apple.eawt or java.awt.Desktop packages to listen to Events that occur when the application is closed, hidden or reactivated.

Particularly com.apple.eawt.AppReOpenedEvent is cast when the Dock Icon is clicked. When you handle the event with com.apple.eawt.AppReOpenedListener, set the frame visible again:

@Override
public void appReOpened(AppReOpenedEvent arg0) {
    invalidate(); // Suppose these are optional, but make sure the layout is up to date
    pack();
    validate();
    setVisible(true);
}

Upvotes: 0

Sergiy Medvynskyy
Sergiy Medvynskyy

Reputation: 11327

Here is a little sample, how to hide/open window in the tray.

import java.awt.Image;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class Test {

    public static void main(String[] args) throws Exception {
        final JFrame frm = new JFrame("Test");
        Image im = Toolkit.getDefaultToolkit().getImage("c:\\icons\\icon1.png");
        final TrayIcon tri = new TrayIcon(im);
        tri.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                frm.setVisible(true);
                try {
                    SystemTray.getSystemTray().remove(tri);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
        frm.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                try {
                    SystemTray.getSystemTray().add(tri);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                frm.setVisible(false);
            }
        });
        frm.setSize(100, 100);
        frm.setVisible(true);
    }
}

Upvotes: 2

Related Questions