Ordinary User
Ordinary User

Reputation: 117

Manage Java CardLayout JPanels created with different classes

I need a simple example of how to manage multiple JPanels (created with different classes) in one JFrame using CardLayout (or something else?). This is an illustrative example of what I need:

Panel A:

enter image description here

Panel B:

enter image description here

Example of file structures:

// Gui.java
public class Gui {
    ...
    ...
    ...
}

// PanelA.java
public class PanelA {
    ...
    ...
    ... () {
        JPanel pnl = new JPanel();
        pnl.setBackground(Color.ORANGE);
        JButton btn = new JButtn("Show Panel B");
        pnl.add(btn);
    }

    public void actionPerformed(ActionEvent ae) {
        ...
    }
}

// PanelB.java
public class PanelB {
    ...
    ...
    ... () {
        JPanel pnl = new JPanel();
        pnl.setBackground(Color.GREEN);
        JButton btn = new JButtn("Show Panel A");
        pnl.add(btn);
    }

    public void actionPerformed(ActionEvent ae) {
        ...
    }
}

I found a lot of examples doing this, but all JPanels were created in the same class with JButtons as fields so the Listener could access to them. I tried to edit those examples but with no success. Sorry for my bad english, Thank You in advance!

Upvotes: 0

Views: 381

Answers (1)

Usagi Miyamoto
Usagi Miyamoto

Reputation: 6299

Try something like this:

Gui.java:

public class Gui {
    ...
    JPanel cards = ne JPanel(new CardLayout());
    private void initComponetns() {
        ...
        // cards to be the container with CardLayout...
        cards.add(new PanelA(this));
        cards.add(new PanelB(this));
        ...
    }
}

PanelA.java

public class PanelA extends JPanel {
    ...
    private final Gui gui;
    PanelA(Gui gui) {
        this.gui = gui;
    }
    ... () {
        setBackground(Color.ORANGE);
        JButton btn = new JButtn("Show Panel B");
        add(btn);
    }

    public void actionPerformed(ActionEvent ae) {
        ...
        gui.cards. ...
    }
}

PanelB.java

public class PanelB extends JPanel {
    ...
    private final Gui gui;
    PanelB(Gui gui) {
        this.gui = gui;
    }
    ...
    ... () {
        setBackground(Color.GREEN);
        JButton btn = new JButtn("Show Panel A");
        add(btn);
    }

    public void actionPerformed(ActionEvent ae) {
        ...
        gui.cards. ...
    }
}

Edited...

Upvotes: 1

Related Questions