Back to TILs

Dispose window

Date: 2019-11-20Last modified: 2023-03-07

Referências

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Teste extends JFrame implements WindowListener{
	public Teste(){
		super("algo");
		setSize(200,200);
		setVisible(true);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		addWindowListener(this);
	}

	public void windowClosing(WindowEvent arg0) {
		JOptionPane.showMessageDialog(null,
				"A janela está fechando!",
				"Dúvida",
				JOptionPane.ERROR_MESSAGE);
	}
	
	public void windowOpened(WindowEvent arg0){
		JOptionPane.showMessageDialog(null,
				"A janela abriu!",
				"Dúvida",
				JOptionPane.ERROR_MESSAGE);
	}

	public void windowClosed(WindowEvent arg0) {}

	public void windowIconified(WindowEvent arg0) {}

	public void windowDeiconified(WindowEvent arg0) {}

	public void windowActivated(WindowEvent arg0) {}

	public void windowDeactivated(WindowEvent arg0) {}
	
	public static void main(String[] args) {
		new Teste();
	}
}

Entendeu? Lembrando que você pode criar outra classe que implemente WindowListener e nela você definir os comandos necessários. Exemplo:

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;

public class Tal implements WindowListener {

	JFrame []s;
	public Tal(JFrame [] s){
		this.s = s;
	}
	
	public void windowOpened(WindowEvent arg0) {}

	public void windowClosing(WindowEvent arg0) {
		for(int i=0;i<s.length;i++)
			s[i].dispose();
	}

	public void windowClosed(WindowEvent arg0) {}

	public void windowIconified(WindowEvent arg0) {}

	public void windowDeiconified(WindowEvent arg0) {}

	public void windowActivated(WindowEvent arg0) {}

	public void windowDeactivated(WindowEvent arg0) {}

}

Aí você faz no construtor da sua janela:

addWindowListener(new Tal(arrayDeJframes)); sendo que arrayDeJFrames são as janelas que você deseja que fechem após fechar essa principal.

Espero ter ajudado. Abraço