Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Window events for JFrames that are hidden/shown via setVisible?

Tags:

java

events

swing

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)?

like image 996
schweerelos Avatar asked Mar 08 '09 00:03

schweerelos


People also ask

What is setVisible () in Java?

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.

How do I hide a JFrame window?

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); .


1 Answers

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 */
   }
});
like image 127
James Avatar answered Oct 14 '22 15:10

James