View Javadoc
1   package com.nilhcem.fakesmtp.gui.listeners;
2   
3   import com.nilhcem.fakesmtp.core.Configuration;
4   import com.nilhcem.fakesmtp.gui.MainFrame;
5   import com.nilhcem.fakesmtp.gui.TrayPopup;
6   import java.awt.AWTException;
7   import java.awt.Frame;
8   import java.awt.Image;
9   import java.awt.SystemTray;
10  import java.awt.Toolkit;
11  import java.awt.TrayIcon;
12  import java.awt.event.ActionEvent;
13  import java.awt.event.ActionListener;
14  import java.awt.event.WindowAdapter;
15  import java.awt.event.WindowEvent;
16  import javax.swing.JFrame;
17  import org.slf4j.Logger;
18  import org.slf4j.LoggerFactory;
19  
20  /**
21   * Responsible for window minimizing and closing. If SystemTray is supported,
22   * the window MainFrame is minimized to an icon.
23   *
24   * @author Vest
25   * @since 2.1
26   */
27  public class MainWindowListener extends WindowAdapter {
28  
29  	private TrayIcon trayIcon;
30  	private final boolean useTray;
31  
32  	private static final Logger LOGGER = LoggerFactory.getLogger(MainWindowListener.class);
33  
34  	/**
35  	 * @param mainFrame The MainFrame class used for closing actions from TrayPopup.
36  	 */
37  	public MainWindowListener(final MainFrame mainFrame) {
38  		useTray = (SystemTray.isSupported() && Boolean.parseBoolean(Configuration.INSTANCE.get("application.tray.use")));
39  
40  		if (useTray) {
41  			final TrayPopup trayPopup = new TrayPopup(mainFrame);
42  
43  			final Image iconImage = Toolkit.getDefaultToolkit().getImage(getClass().
44  				getResource(Configuration.INSTANCE.get("application.icon.path")));
45  
46  			trayIcon = new TrayIcon(iconImage);
47  
48  			trayIcon.setImageAutoSize(true);
49  			trayIcon.setPopupMenu(trayPopup.get());
50  		}
51  	}
52  
53  	@Override
54  	public void windowStateChanged(WindowEvent e) {
55  		super.windowStateChanged(e);
56  		if (!useTray) {
57  			return;
58  		}
59  
60  		final SystemTray tray = SystemTray.getSystemTray();
61  		final JFrame frame = (JFrame) e.getSource();
62  
63  		if ((e.getNewState() & Frame.ICONIFIED) != 0) {
64  			try {
65  				/* Displays the window when the icon is clicked twice */
66  				trayIcon.addActionListener(new ActionListener() {
67  					@Override
68  					public void actionPerformed(ActionEvent ae) {
69  						int state = frame.getExtendedState();
70  						state &= ~Frame.ICONIFIED;
71  
72  						frame.setExtendedState(state);
73  						frame.setVisible(true);
74  
75  						tray.remove(trayIcon);
76  
77  						trayIcon.removeActionListener(this);
78  					}
79  				});
80  
81  				tray.add(trayIcon);
82  				frame.dispose();
83  			} catch (AWTException ex) {
84  				LOGGER.error("Couldn't create a tray icon, the minimizing is not possible", ex);
85  			}
86  		} else {
87  			frame.setVisible(true);
88  		}
89  	}
90  }