Estou com um problema,
Como posso fechar um JFrame e ocorrer o efeito como se eu tivesse pressionando a tecla “ALT + F4”?
O hide(), dispose(), setVisible(false) não fazem o mesmo efeito.
vou colocar um exemplo do que estou dizendo. Alguém tem uma solução?
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class FecharJFrame extends JFrame {
public FecharJFrame() {
super (“Como Fechar um JFrame”);
Container tela = getContentPane();
tela.setLayout(new FlowLayout());
JButton btn = new JButton("Abrir Outro JFrame");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SeguntaTela segTela = new SeguntaTela();
segTela.setVisible(true);
}
});
tela.add(btn);
setSize(300, 150);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
FecharJFrame app = new FecharJFrame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class SeguntaTela extends JFrame {
public SeguntaTela() {
super (“Quero Fechar essa Tela”);
Container tela = getContentPane();
tela.setLayout(new FlowLayout());
JButton btn = new JButton("hide()");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hide();
}
});
JButton btn2 = new JButton("dispose()");
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
JButton btn3 = new JButton("setVisible(false)");
btn3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
JButton btn4 = new JButton("System.exit(0)");
btn4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JLabel label = new JLabel("Experimente Fechar com 'ALT + F4' ou 'X' da Barra de Titulos");
JLabel label2 = new JLabel("Alguém sabe fechar com mesmo efeito do 'ALT + F4'?");
tela.add(btn);
tela.add(btn2);
tela.add(btn3);
tela.add(btn4);
tela.add(label);
tela.add(label2);
EventWindowClosing eventClosing = new EventWindowClosing(this);
this.addWindowListener(eventClosing);
setSize(600, 150);
setLocationRelativeTo(null);
}
}
private class EventWindowClosing extends WindowAdapter {
private JFrame owner;
public EventWindowClosing(JFrame owner) {
this.owner = owner;
}
public void windowClosing(WindowEvent e) {
JOptionPane.showMessageDialog(owner, "Fechou Corretamente.", "Informação",
JOptionPane.INFORMATION_MESSAGE);
}
}
}