Como faço para fechar um JFrame assim:
Eu abro um formulário (o principal da aplicação). Neste formulário principal eu tenho dois botões: um botão que abre outro formulário e um outro botão que fecha esse segundo formulário.
Alguém me ajuda?
Como faço para fechar um JFrame assim:
Eu abro um formulário (o principal da aplicação). Neste formulário principal eu tenho dois botões: um botão que abre outro formulário e um outro botão que fecha esse segundo formulário.
Alguém me ajuda?
Exemplinho:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestFrame {
private JFrame frame1;
private JFrame frame2;
private JButton buttonAbrir;
private JButton buttonFechar;
public TestFrame() {
frame1 = new JFrame("JFrame1");
initialize();
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize(400, 400);
frame1.setLocationRelativeTo(null);
frame1.setVisible(true);
}
private void initialize() {
frame1.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
ButtonHandler buttonHandler = new ButtonHandler();
buttonAbrir = new JButton("Abrir");
buttonAbrir.addActionListener(buttonHandler);
buttonFechar = new JButton("Fechar");
buttonFechar.addActionListener(buttonHandler);
JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 10, 10));
buttonPanel.add(buttonAbrir);
buttonPanel.add(buttonFechar);
frame1.getContentPane().add(buttonPanel);
}
private JFrame getFrame2(String title) {
if (frame2 == null) {
frame2 = new JFrame(title);
frame2.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
frame2.getContentPane().add(new JLabel(title));
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame2.setSize(200, 200);
frame2.setLocationRelativeTo(frame1);
}
return frame2;
}
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent ev) {
Object obj = ev.getSource();
if (obj == buttonAbrir) {
getFrame2("JFrame2").setVisible(true);
} else if (obj == buttonFechar) {
if (frame2 != null) {
frame2.dispose();
frame2 = null;
}
}
}
}
public static void main(String[] args) {
new TestFrame();
}
}
Valeu!!
Muito interessante - funcionou 100%