Which kind of listener do I have to add to a JFrame
to detect when it is being hidden or shown via setVisible
?
I tried using a WindowListener
and the windowOpened
and windowClosed
methods, but they only work for the first time that a window is opened (windowOpened
) or, respectively, when the window is closed using the dispose method (windowClosed
). That is not enough for me. I want to be notified every time the window is made visible and invisible on the screen using setVisible
.
Is there a standard Swing way to achieve this, or do I need to make my own (by, say, overriding the setVisible
method)?
The setVisible(true) method makes the frame appear on the screen. If you forget to do this, the frame object will exist as an object in memory, but no picture will appear on the screen.
Just add this: JFrame. setDefaultCloseOperation(DISPOSE_ON_CLOSE) . Note: The default option for JFrame is HIDE_ON_CLOSE . This will cause the program to slow down much like setVisible(false); .
Try a java.awt.event.ComponentListener
. You can add one using this code (where window is the name of the JFrame
) :
window.addComponentListener(new ComponentAdapter() {
public void componentHidden(ComponentEvent e) {
/* code run when component hidden*/
}
public void componentShown(ComponentEvent e) {
/* code run when component shown */
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With