devxlogo

Switching Between Frames

Switching Between Frames

Question:
I’m building an application that has several different frames. Eachhas a button that when pressed should bring up a new frame and closethe calling frame. How can I display the new frame and closethe calling frame?

Answer:
Creating a new frame is as simple as following the same steps youfollowed when creating the original frame. Closing the callingframe requires a little bit of care. You should make sure you createthe new frame before closing and disposing of the old frame. Oneway of doing this is to hide the old frame, create and display thenew frame, and then dispose of the old frame.

The following code demonstrates how to do this. It creates a frame with anexit button and a button for creating new frames. It registers anActionListener with the exit button to exit the entire application.The ActionListener it registers with the new frame button takes careof hiding the old frame, creating the new frame, and disposing ofthe old frame. Keep in mind that an alternative to creating a newframe is to reuse the old frame, simply replacing its contents witha 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);  }}

devx-admin

Share the Post: