What JFrame event allows me to execute a method while the JFrame is Open?

0

I am looking to implement an event of JFrame that allows executing a method as long as the JFRAME is active,

If the method exists, can someone give me the name and an implementation example?

PS: I tried the event windowActivated but it did not work.

    
asked by Diego Fernando Barrios Olmos 29.03.2017 в 22:35
source

3 answers

2

The WindowListener Class is for this purpose, to listen events that have to do with the window (JFrame in this case). These events are:

  • Activates windowActivated
  • Off windowDeactivated
  • Minimized windowDeiconified
  • Maximized windowIconified
  • Open windowOpened
  • Closed windowClosed

Its use is like this:

    JFrame frame = new JFrame();
    frame.setSize(200, 200);
    frame.setVisible(true);
    frame.addWindowListener(new EscuchaJFrame());

class EscuchaJFrame implements WindowListener{
    public void windowActivated(WindowEvent e){
        System.out.println("Ventana Activada ");
        MethodoaEjecutar();
    }

    public void windowClosed(WindowEvent e){
        System.out.println("Ventada Closed Dispose");
    }

    public void windowClosing(WindowEvent e){
        System.out.println("Ventana Closing");
    }

    public void windowDeactivated(WindowEvent e){
        System.out.println("Ventana Desactivada");
    }

    public void windowDeiconified(WindowEvent e){
        System.out.println("Windows de Maximizada a Normal");
    }

    public void windowIconified(WindowEvent e){
        System.out.println("Windows de Normal a Maximizada");
    }

    public void windowOpened(WindowEvent e){
        System.out.println("Windows Abierta");
    }

}
    
answered by 29.03.2017 в 23:23
0

You can try the isActive () method. Example, if your class inherits from JFrame you can try like this:

if(this.isActive()){

//llamar al metodo que necesito }

    
answered by 29.03.2017 в 22:58
0

Thank you very much for your collaboration, debug the program, restart Eclipse and it worked. My code stayed like this:

//Constructor de la clase
public myClass(){

  addWindowListener(new java.awt.event.WindowAdapter(){

        public void windowOpened(java.awt.event.WindowEvent evt){
            //code
        }

        public void windowClosing(java.awt.event.WindowEvent evt){
            //code
        }

        public void windowActivated(java.awt.event.WindowEvent evt){
            //code
        }
  }

}
    
answered by 30.03.2017 в 02:29