this is old but i would like to share how i handle this kind of requirement:
import java.awt.Color;
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.JOptionPane;
public class multipleFrames extends JFrame {
static JFrame mainFrame;
static JFrame secondFrame;
public multipleFrames() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// Create the main frame
openMainFrame();
}
protected static void openSecondFrame() {
// TODO Auto-generated method stub
secondFrame = new JFrame("Second Frame");
// secondFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
secondFrame.setSize(400, 200);
secondFrame.setLayout(new FlowLayout());
secondFrame.setLocationRelativeTo(mainFrame);
secondFrame.getContentPane().setBackground(Color.decode("#3d8500"));
secondFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
JOptionPane.showMessageDialog(secondFrame,"Disposing secondFrame ...","Message",JOptionPane.PLAIN_MESSAGE);
secondFrame.dispose();
// clear secondFrame references to destroy it
secondFrame = null;
}
});
// Create buttons
JButton backButton = new JButton("Back to Main Frame");
backButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// secondFrame.setVisible(false);
if (mainFrame==null) {
JOptionPane.showMessageDialog(secondFrame,"mainFrame not exist, creating ...","Message",JOptionPane.PLAIN_MESSAGE);
openMainFrame();
}else {
mainFrame.setVisible(true);
mainFrame.toFront();
}
}
});
secondFrame.add(backButton);
secondFrame.setVisible(true);
}
protected static void openMainFrame() {
// TODO Auto-generated method stub
mainFrame = new JFrame("Main Frame");
// mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainFrame.setSize(400, 200);
mainFrame.setLayout(new FlowLayout());
mainFrame.setLocationRelativeTo(secondFrame);
mainFrame.getContentPane().setBackground(Color.decode("#3d85c6"));
mainFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
JOptionPane.showMessageDialog(mainFrame,"Disposing mainFrame ...","Message",JOptionPane.PLAIN_MESSAGE);
mainFrame.dispose();
// clear manFrame references to destroy it
mainFrame = null;
}
});
// Create buttons
JButton secondButton = new JButton("Open Second Frame");
secondButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// mainFrame.setVisible(false);
if (secondFrame==null) {
JOptionPane.showMessageDialog(mainFrame,"secondFrame not exist, creating ...","Message",JOptionPane.PLAIN_MESSAGE);
openSecondFrame();
}else {
secondFrame.setVisible(true);
secondFrame.toFront();
}
}
});
mainFrame.add(secondButton);
mainFrame.setVisible(true);
}
}