Skip to content

Commit 615e383

Browse files
committed
Static utility to add onClose events when a JComponent is closed.
1 parent 5b3181e commit 615e383

1 file changed

Lines changed: 33 additions & 1 deletion

File tree

src/main/java/fiji/plugin/trackmate/gui/GuiUtils.java

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,16 @@
3232
import java.awt.color.ColorSpace;
3333
import java.awt.event.FocusEvent;
3434
import java.awt.event.FocusListener;
35+
import java.awt.event.WindowAdapter;
3536

37+
import javax.swing.JComponent;
3638
import javax.swing.JOptionPane;
3739
import javax.swing.JTextField;
3840
import javax.swing.SwingUtilities;
3941
import javax.swing.UIManager;
4042
import javax.swing.UnsupportedLookAndFeelException;
43+
import javax.swing.event.AncestorEvent;
44+
import javax.swing.event.AncestorListener;
4145

4246
import ij.IJ;
4347
import ij.ImagePlus;
@@ -146,7 +150,7 @@ public static final float[] toCIELab( final Color color )
146150
return fromCIEXYZ( xyz );
147151
}
148152

149-
public static final Color invert(final Color color)
153+
public static final Color invert( final Color color )
150154
{
151155
return new Color( 255 - color.getRed(),
152156
255 - color.getGreen(),
@@ -242,4 +246,32 @@ public static void setSystemLookAndFeel()
242246

243247
}
244248
}
249+
250+
public static void addOnClosingEvent( final JComponent component, final Runnable runnable )
251+
{
252+
component.addAncestorListener( new AncestorListener()
253+
{
254+
255+
@Override
256+
public void ancestorRemoved( final AncestorEvent event )
257+
{}
258+
259+
@Override
260+
public void ancestorMoved( final AncestorEvent event )
261+
{}
262+
263+
@Override
264+
public void ancestorAdded( final AncestorEvent event )
265+
{
266+
SwingUtilities.getWindowAncestor( component ).addWindowListener( new WindowAdapter()
267+
{
268+
@Override
269+
public void windowClosing( final java.awt.event.WindowEvent e )
270+
{
271+
runnable.run();
272+
};
273+
} );
274+
}
275+
} );
276+
}
245277
}

0 commit comments

Comments
 (0)