Question:
I'm building an application that has several different frames. Each
has a button that when pressed should bring up a new frame and close
the calling frame. How can I display the new frame and close
the calling frame?
Answer:
Creating a new frame is as simple as following the same steps you
followed when creating the original frame. Closing the calling
frame requires a little bit of care. You should make sure you create
the new frame before closing and disposing of the old frame. One
way of doing this is to hide the old frame, create and display the
new frame, and then dispose of the old frame.
The following code demonstrates how to do this. It creates a frame with an
exit button and a button for creating new frames. It registers an
ActionListener with the exit button to exit the entire application.
The ActionListener it registers with the new frame button takes care
of hiding the old frame, creating the new frame, and disposing of
the old frame. Keep in mind that an alternative to creating a new
frame is to reuse the old frame, simply replacing its contents with
a new component panel.
import java.awt.*;
import java.awt.event.*;
public class Frames {
public static class NewFrame extends Frame {
int _id;
Button _exitButton, _newFrameButton;
public NewFrame(int id) {
_id = id;
_exitButton = new Button("Exit");
_newFrameButton = new Button("New Frame");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Window window = e.getWindow();
window.setVisible(false);
window.dispose();
System.exit(0);
}
});
_exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose();
System.exit(0);
}
});
_newFrameButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Frame frame;
setVisible(false);
frame = new NewFrame(_id + 1);
frame.pack();
frame.setVisible(true);
dispose();
}
});
setLayout(new FlowLayout());
add(_exitButton);
add(_newFrameButton);
setTitle("Frame #" + id);
}
}
public static final void main(String[] args) {
NewFrame frame;
frame = new NewFrame(0);
frame.pack();
frame.setVisible(true);
}
}