How to catch the window minimization event?

I want to create a JFrame instance and click its minimize button , I would like to hide it until System Tray , which is usually the taskbar for windows.

I would find out that using the SystemTray in the java.awt , I can do this, but neither do I get any tutorial on it, nor any example work program.

I asked this question here to get a link to a tutorial site for the SystemTray or if any authority knows how to lure a window minimization event, a working example.

+6
source share
5 answers

This will catch the event with minimizing the window and create a tray icon. It will also remove the window from the taskbar and add a listener to the tray icon so that mouseclick restores the window. The code is a little patchwork, but should be good enough for your training purposes:

 public class Qwe extends JFrame { public static void main(String[] args) { final Qwe qwe = new Qwe(); qwe.addWindowStateListener(new WindowStateListener() { public void windowStateChanged(WindowEvent e) { if (e.getNewState() == ICONIFIED) { try { final TrayIcon trayIcon = new TrayIcon(new ImageIcon("/usr/share/icons/gnome/16x16/emotes/face-plain.png").getImage()); trayIcon.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { qwe.setVisible(true); SystemTray.getSystemTray().remove(trayIcon); } }); SystemTray.getSystemTray().add(trayIcon); qwe.setVisible(false); } catch (AWTException e1) { e1.printStackTrace(); } } } }); qwe.setSize(200, 200); qwe.setVisible(true); } } 
+4
source

The interface of WindowListener and JFrame addWindowListener() should help you determine when the frame has been minimized.

+5
source

the best way will be created

1) SystemTray

2) add JPopopMenu to SystemTray Icon

3) set DefaultCloseOperation for TopLevelContainer (in your case, JFrame )

  • using WindowListener setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

  • in other cases, setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); always works setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

  • do not forget to declare System.exit(1) SystemTray JpopupMenu , from JMenuItem or another Action/Event , because in this form currenet JVM never switched from the native OS until the PC shuts down or reboots

+2
source
 private void windowStateChanged(java.awt.event.WindowEvent evt) { // Use getExtendedstate here. } 
+1
source
 frame.addWindowListener(new WindowAdapter() {@Override public void windowIconified(WindowEvent e) {} }); 
0
source

Source: https://habr.com/ru/post/902017/


All Articles