You don't need to use a CardLayout for anything in this case. In fact, JFrame's don't have layouts.
Here's some code to illustrate that idea (assuming you're using Java 8; otherwise, add the final
modifier to oldFrame
and newFrame
:
JFrame parent = new JFrame();
JDialog oldFrame = new JDialog("My Old Frame's Title");
JDialog newFrame = new JDialog("My New Frame's Title");
JPanel panel = new JPanel();
JButton myButton = new JButton();
myButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
oldFrame.dispose(); //closes your old frame
newFrame.setVisible(true); //opens your new frame
}
});
panel.add(myButton);
oldFrame.add(panek);
oldFrame.setVisible(true);
Whenever you click your button, the old frame closes, and the new one opens.