Is it possible to perform some action before the JFrame is minimized?

In Swing, there are several ways to capture the frame minimization event (display), but the event occurs when the frame is ICONIFIED, which means that after the frame becomes invisible from the screen.

Now I want to run the code before the frame disappears - right away when I click the taskbar button .

In other words, do something when the JFrame "about" (NOT AFTER) is minimized . Can this be done?

+4
source share
3 answers

Use a WindowStateListener and call WindowEvent#getNewState() and check the Frame.ICONIFIED checkbox.

Here is an example:

 import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JPanel; public class Test { public Test() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel() { @Override public Dimension getPreferredSize() { return new Dimension(300, 300); } }; frame.add(panel); frame.addWindowStateListener(new WindowAdapter() { @Override public void windowStateChanged(WindowEvent we) { if (we.getNewState() == Frame.ICONIFIED) { System.out.println("Here"); } } }); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new Test(); } }); } } 
+3
source

Create your own JFrame method and override setExtendedState .

 public class MyFrame extends JFrame{ .... setExtendedState(JFrame.ICONIFIED); .... @Override public void setExtendedState(int state) { // your code super.setExtendedState(state); }; } 
0
source

Answer the question "Is it possible to perform any action before the JFrame is minimized?"

I would say no, unfortunately, I checked my own code for openjdk (windows) for frame and window , which sends these events to java space. And, as I understand it, this is a callback from the VM_SIZE message API window. And SIZE_MINIMIZED sent when the "Window has been minimized" and does not receive any messages until it is actually minimized.

0
source

All Articles