3.14ed_Piper
3.14ed_Piper

Reputation: 151

CardLayout for JFrames?

I've been looking around, including in the Java documentation, but there isn't a clear answer that I've found for my question : I would like to switch from one JFrame to another at the click of a button; that is, have the old JFrame close while the new one opens. I've heard of "CardLayout" but I'm not so sure how it works. Would anyone mind explaining it, or some other method?

Thanks

Upvotes: 0

Views: 4055

Answers (2)

Jonah
Jonah

Reputation: 1003

Here is an example of a CardLayout

As you've heard other say, don't use multiple JFrames.

import javax.swing.*;
import java.awt.*;

public class MainFrame
{
static JPanel homeContainer;
static JPanel homePanel;
static JPanel otherPanel;
static CardLayout cl;

public MainFrame()
{
    JFrame mFrame = new JFrame("CardLayout Example");
    JButton showOtherPanelBtn = new JButton("Show Other Panel");
    JButton backToHomeBtn = new JButton("Show Home Panel");

    cl = new CardLayout(5, 5);
    homeContainer = new JPanel(cl);
    homeContainer.setBackground(Color.black);

    homePanel = new JPanel();
    homePanel.setBackground(Color.blue);
    homePanel.add(showOtherPanelBtn);

    homeContainer.add(homePanel, "Home");

    otherPanel = new JPanel();
    otherPanel.setBackground(Color.green);
    otherPanel.add(backToHomeBtn);

    homeContainer.add(otherPanel, "Other Panel");

    showOtherPanelBtn.addActionListener(e -> cl.show(homeContainer, "Other Panel"));
    backToHomeBtn.addActionListener(e -> cl.show(homeContainer, "Home"));

    mFrame.add(homeContainer);
    cl.show(homeContainer, "Home");
    mFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    mFrame.setLocationRelativeTo(null);
    mFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    mFrame.pack();
    mFrame.setVisible(true);
}

public static void main(String[] args)
{
    SwingUtilities.invokeLater(MainFrame::new);
}
}

Upvotes: 3

Lucas Baizer
Lucas Baizer

Reputation: 325

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.

Upvotes: 0

Related Questions